contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
setInversePricing
function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } }
/** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 13733, 15285 ] }
12,300
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
removeInversePricing
function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } }
/** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 15432, 16032 ] }
12,301
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
addAggregator
function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); }
/** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 16223, 16700 ] }
12,302
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
removeFromArray
function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; }
/** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 16954, 17631 ] }
12,303
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
removeAggregator
function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } }
/** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 17780, 18199 ] }
12,304
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
effectiveValue
function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); }
/** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 18586, 19251 ] }
12,305
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
rateForCurrency
function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); }
/** * @notice Retrieve the rate for a specific currency */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 19326, 19473 ] }
12,306
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
ratesForCurrencies
function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; }
/** * @notice Retrieve the rates for a list of currencies */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 19550, 19889 ] }
12,307
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
ratesAndStaleForCurrencies
function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); }
/** * @notice Retrieve the rates and isAnyStale for a list of currencies */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 19981, 20691 ] }
12,308
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
rateIsStale
function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; }
/** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 20814, 21102 ] }
12,309
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
rateIsFrozen
function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; }
/** * @notice Check if any rate is frozen (cannot be exchanged into) */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 21190, 21352 ] }
12,310
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
anyRateIsStale
function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; }
/** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 21486, 22009 ] }
12,311
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SynthetixState
contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } // Issued synth balances for individual fee entitlements and exit price calculations mapping(address => IssuanceData) public issuanceData; // The total count of people that have outstanding issued synths in any flavour uint public totalIssuerCount; // Global debt pool tracking uint[] public debtLedger; // Import state uint public importedXDRAmount; // A quantity of synths greater than this ratio // may not be issued against a given value of SNX. uint public issuanceRatio = SafeDecimalMath.unit() / 5; // No more synths may be issued than the value of SNX backing them. uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); // Users can specify their preferred currency, in which case all synths they receive // will automatically exchange to that preferred currency upon receipt in their wallet mapping(address => bytes4) public preferredCurrency; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} /* ========== SETTERS ========== */ /** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */ function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } /** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */ function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } /** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */ function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } /** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */ function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } /** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */ function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } /** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */ function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */ function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */ function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we've previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the debt ledger array */ function debtLedgerLength() external view returns (uint) { return debtLedger.length; } /** * @notice Retrieve the most recent entry from the debt ledger */ function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } /** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */ function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); }
/** * @title Synthetix State * @notice Stores issuance information and preferred currency information of the Synthetix contract. */
NatSpecMultiLine
setCurrentIssuanceData
function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; }
/** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 2371, 2651 ] }
12,312
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SynthetixState
contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } // Issued synth balances for individual fee entitlements and exit price calculations mapping(address => IssuanceData) public issuanceData; // The total count of people that have outstanding issued synths in any flavour uint public totalIssuerCount; // Global debt pool tracking uint[] public debtLedger; // Import state uint public importedXDRAmount; // A quantity of synths greater than this ratio // may not be issued against a given value of SNX. uint public issuanceRatio = SafeDecimalMath.unit() / 5; // No more synths may be issued than the value of SNX backing them. uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); // Users can specify their preferred currency, in which case all synths they receive // will automatically exchange to that preferred currency upon receipt in their wallet mapping(address => bytes4) public preferredCurrency; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} /* ========== SETTERS ========== */ /** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */ function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } /** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */ function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } /** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */ function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } /** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */ function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } /** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */ function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } /** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */ function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */ function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */ function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we've previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the debt ledger array */ function debtLedgerLength() external view returns (uint) { return debtLedger.length; } /** * @notice Retrieve the most recent entry from the debt ledger */ function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } /** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */ function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); }
/** * @title Synthetix State * @notice Stores issuance information and preferred currency information of the Synthetix contract. */
NatSpecMultiLine
clearIssuanceData
function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; }
/** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 2832, 2977 ] }
12,313
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SynthetixState
contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } // Issued synth balances for individual fee entitlements and exit price calculations mapping(address => IssuanceData) public issuanceData; // The total count of people that have outstanding issued synths in any flavour uint public totalIssuerCount; // Global debt pool tracking uint[] public debtLedger; // Import state uint public importedXDRAmount; // A quantity of synths greater than this ratio // may not be issued against a given value of SNX. uint public issuanceRatio = SafeDecimalMath.unit() / 5; // No more synths may be issued than the value of SNX backing them. uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); // Users can specify their preferred currency, in which case all synths they receive // will automatically exchange to that preferred currency upon receipt in their wallet mapping(address => bytes4) public preferredCurrency; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} /* ========== SETTERS ========== */ /** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */ function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } /** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */ function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } /** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */ function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } /** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */ function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } /** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */ function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } /** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */ function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */ function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */ function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we've previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the debt ledger array */ function debtLedgerLength() external view returns (uint) { return debtLedger.length; } /** * @notice Retrieve the most recent entry from the debt ledger */ function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } /** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */ function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); }
/** * @title Synthetix State * @notice Stores issuance information and preferred currency information of the Synthetix contract. */
NatSpecMultiLine
incrementTotalIssuerCount
function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); }
/** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 3099, 3251 ] }
12,314
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SynthetixState
contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } // Issued synth balances for individual fee entitlements and exit price calculations mapping(address => IssuanceData) public issuanceData; // The total count of people that have outstanding issued synths in any flavour uint public totalIssuerCount; // Global debt pool tracking uint[] public debtLedger; // Import state uint public importedXDRAmount; // A quantity of synths greater than this ratio // may not be issued against a given value of SNX. uint public issuanceRatio = SafeDecimalMath.unit() / 5; // No more synths may be issued than the value of SNX backing them. uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); // Users can specify their preferred currency, in which case all synths they receive // will automatically exchange to that preferred currency upon receipt in their wallet mapping(address => bytes4) public preferredCurrency; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} /* ========== SETTERS ========== */ /** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */ function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } /** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */ function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } /** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */ function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } /** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */ function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } /** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */ function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } /** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */ function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */ function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */ function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we've previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the debt ledger array */ function debtLedgerLength() external view returns (uint) { return debtLedger.length; } /** * @notice Retrieve the most recent entry from the debt ledger */ function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } /** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */ function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); }
/** * @title Synthetix State * @notice Stores issuance information and preferred currency information of the Synthetix contract. */
NatSpecMultiLine
decrementTotalIssuerCount
function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); }
/** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 3373, 3525 ] }
12,315
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SynthetixState
contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } // Issued synth balances for individual fee entitlements and exit price calculations mapping(address => IssuanceData) public issuanceData; // The total count of people that have outstanding issued synths in any flavour uint public totalIssuerCount; // Global debt pool tracking uint[] public debtLedger; // Import state uint public importedXDRAmount; // A quantity of synths greater than this ratio // may not be issued against a given value of SNX. uint public issuanceRatio = SafeDecimalMath.unit() / 5; // No more synths may be issued than the value of SNX backing them. uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); // Users can specify their preferred currency, in which case all synths they receive // will automatically exchange to that preferred currency upon receipt in their wallet mapping(address => bytes4) public preferredCurrency; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} /* ========== SETTERS ========== */ /** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */ function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } /** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */ function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } /** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */ function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } /** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */ function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } /** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */ function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } /** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */ function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */ function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */ function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we've previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the debt ledger array */ function debtLedgerLength() external view returns (uint) { return debtLedger.length; } /** * @notice Retrieve the most recent entry from the debt ledger */ function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } /** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */ function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); }
/** * @title Synthetix State * @notice Stores issuance information and preferred currency information of the Synthetix contract. */
NatSpecMultiLine
appendDebtLedgerValue
function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); }
/** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 3714, 3852 ] }
12,316
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SynthetixState
contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } // Issued synth balances for individual fee entitlements and exit price calculations mapping(address => IssuanceData) public issuanceData; // The total count of people that have outstanding issued synths in any flavour uint public totalIssuerCount; // Global debt pool tracking uint[] public debtLedger; // Import state uint public importedXDRAmount; // A quantity of synths greater than this ratio // may not be issued against a given value of SNX. uint public issuanceRatio = SafeDecimalMath.unit() / 5; // No more synths may be issued than the value of SNX backing them. uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); // Users can specify their preferred currency, in which case all synths they receive // will automatically exchange to that preferred currency upon receipt in their wallet mapping(address => bytes4) public preferredCurrency; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} /* ========== SETTERS ========== */ /** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */ function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } /** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */ function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } /** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */ function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } /** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */ function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } /** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */ function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } /** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */ function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */ function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */ function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we've previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the debt ledger array */ function debtLedgerLength() external view returns (uint) { return debtLedger.length; } /** * @notice Retrieve the most recent entry from the debt ledger */ function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } /** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */ function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); }
/** * @title Synthetix State * @notice Stores issuance information and preferred currency information of the Synthetix contract. */
NatSpecMultiLine
setPreferredCurrency
function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; }
/** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 4096, 4276 ] }
12,317
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SynthetixState
contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } // Issued synth balances for individual fee entitlements and exit price calculations mapping(address => IssuanceData) public issuanceData; // The total count of people that have outstanding issued synths in any flavour uint public totalIssuerCount; // Global debt pool tracking uint[] public debtLedger; // Import state uint public importedXDRAmount; // A quantity of synths greater than this ratio // may not be issued against a given value of SNX. uint public issuanceRatio = SafeDecimalMath.unit() / 5; // No more synths may be issued than the value of SNX backing them. uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); // Users can specify their preferred currency, in which case all synths they receive // will automatically exchange to that preferred currency upon receipt in their wallet mapping(address => bytes4) public preferredCurrency; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} /* ========== SETTERS ========== */ /** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */ function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } /** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */ function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } /** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */ function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } /** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */ function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } /** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */ function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } /** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */ function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */ function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */ function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we've previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the debt ledger array */ function debtLedgerLength() external view returns (uint) { return debtLedger.length; } /** * @notice Retrieve the most recent entry from the debt ledger */ function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } /** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */ function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); }
/** * @title Synthetix State * @notice Stores issuance information and preferred currency information of the Synthetix contract. */
NatSpecMultiLine
setIssuanceRatio
function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); }
/** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 4407, 4705 ] }
12,318
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SynthetixState
contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } // Issued synth balances for individual fee entitlements and exit price calculations mapping(address => IssuanceData) public issuanceData; // The total count of people that have outstanding issued synths in any flavour uint public totalIssuerCount; // Global debt pool tracking uint[] public debtLedger; // Import state uint public importedXDRAmount; // A quantity of synths greater than this ratio // may not be issued against a given value of SNX. uint public issuanceRatio = SafeDecimalMath.unit() / 5; // No more synths may be issued than the value of SNX backing them. uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); // Users can specify their preferred currency, in which case all synths they receive // will automatically exchange to that preferred currency upon receipt in their wallet mapping(address => bytes4) public preferredCurrency; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} /* ========== SETTERS ========== */ /** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */ function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } /** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */ function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } /** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */ function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } /** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */ function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } /** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */ function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } /** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */ function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */ function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */ function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we've previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the debt ledger array */ function debtLedgerLength() external view returns (uint) { return debtLedger.length; } /** * @notice Retrieve the most recent entry from the debt ledger */ function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } /** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */ function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); }
/** * @title Synthetix State * @notice Stores issuance information and preferred currency information of the Synthetix contract. */
NatSpecMultiLine
importIssuerData
function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } }
/** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 4897, 5238 ] }
12,319
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SynthetixState
contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } // Issued synth balances for individual fee entitlements and exit price calculations mapping(address => IssuanceData) public issuanceData; // The total count of people that have outstanding issued synths in any flavour uint public totalIssuerCount; // Global debt pool tracking uint[] public debtLedger; // Import state uint public importedXDRAmount; // A quantity of synths greater than this ratio // may not be issued against a given value of SNX. uint public issuanceRatio = SafeDecimalMath.unit() / 5; // No more synths may be issued than the value of SNX backing them. uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); // Users can specify their preferred currency, in which case all synths they receive // will automatically exchange to that preferred currency upon receipt in their wallet mapping(address => bytes4) public preferredCurrency; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} /* ========== SETTERS ========== */ /** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */ function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } /** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */ function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } /** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */ function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } /** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */ function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } /** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */ function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } /** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */ function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */ function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */ function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we've previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the debt ledger array */ function debtLedgerLength() external view returns (uint) { return debtLedger.length; } /** * @notice Retrieve the most recent entry from the debt ledger */ function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } /** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */ function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); }
/** * @title Synthetix State * @notice Stores issuance information and preferred currency information of the Synthetix contract. */
NatSpecMultiLine
_addToDebtRegister
function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we've previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } }
/** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 5417, 7835 ] }
12,320
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SynthetixState
contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } // Issued synth balances for individual fee entitlements and exit price calculations mapping(address => IssuanceData) public issuanceData; // The total count of people that have outstanding issued synths in any flavour uint public totalIssuerCount; // Global debt pool tracking uint[] public debtLedger; // Import state uint public importedXDRAmount; // A quantity of synths greater than this ratio // may not be issued against a given value of SNX. uint public issuanceRatio = SafeDecimalMath.unit() / 5; // No more synths may be issued than the value of SNX backing them. uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); // Users can specify their preferred currency, in which case all synths they receive // will automatically exchange to that preferred currency upon receipt in their wallet mapping(address => bytes4) public preferredCurrency; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} /* ========== SETTERS ========== */ /** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */ function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } /** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */ function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } /** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */ function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } /** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */ function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } /** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */ function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } /** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */ function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */ function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */ function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we've previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the debt ledger array */ function debtLedgerLength() external view returns (uint) { return debtLedger.length; } /** * @notice Retrieve the most recent entry from the debt ledger */ function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } /** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */ function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); }
/** * @title Synthetix State * @notice Stores issuance information and preferred currency information of the Synthetix contract. */
NatSpecMultiLine
debtLedgerLength
function debtLedgerLength() external view returns (uint) { return debtLedger.length; }
/** * @notice Retrieve the length of the debt ledger array */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 7952, 8082 ] }
12,321
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SynthetixState
contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } // Issued synth balances for individual fee entitlements and exit price calculations mapping(address => IssuanceData) public issuanceData; // The total count of people that have outstanding issued synths in any flavour uint public totalIssuerCount; // Global debt pool tracking uint[] public debtLedger; // Import state uint public importedXDRAmount; // A quantity of synths greater than this ratio // may not be issued against a given value of SNX. uint public issuanceRatio = SafeDecimalMath.unit() / 5; // No more synths may be issued than the value of SNX backing them. uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); // Users can specify their preferred currency, in which case all synths they receive // will automatically exchange to that preferred currency upon receipt in their wallet mapping(address => bytes4) public preferredCurrency; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} /* ========== SETTERS ========== */ /** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */ function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } /** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */ function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } /** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */ function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } /** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */ function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } /** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */ function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } /** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */ function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */ function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */ function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we've previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the debt ledger array */ function debtLedgerLength() external view returns (uint) { return debtLedger.length; } /** * @notice Retrieve the most recent entry from the debt ledger */ function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } /** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */ function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); }
/** * @title Synthetix State * @notice Stores issuance information and preferred currency information of the Synthetix contract. */
NatSpecMultiLine
lastDebtLedgerEntry
function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; }
/** * @notice Retrieve the most recent entry from the debt ledger */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 8167, 8316 ] }
12,322
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SynthetixState
contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; // A struct for handing values associated with an individual user's debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user's exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } // Issued synth balances for individual fee entitlements and exit price calculations mapping(address => IssuanceData) public issuanceData; // The total count of people that have outstanding issued synths in any flavour uint public totalIssuerCount; // Global debt pool tracking uint[] public debtLedger; // Import state uint public importedXDRAmount; // A quantity of synths greater than this ratio // may not be issued against a given value of SNX. uint public issuanceRatio = SafeDecimalMath.unit() / 5; // No more synths may be issued than the value of SNX backing them. uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); // Users can specify their preferred currency, in which case all synths they receive // will automatically exchange to that preferred currency upon receipt in their wallet mapping(address => bytes4) public preferredCurrency; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} /* ========== SETTERS ========== */ /** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */ function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } /** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */ function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } /** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */ function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } /** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */ function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } /** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */ function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } /** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */ function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */ function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */ function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we've previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the debt ledger array */ function debtLedgerLength() external view returns (uint) { return debtLedger.length; } /** * @notice Retrieve the most recent entry from the debt ledger */ function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } /** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */ function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); }
/** * @title Synthetix State * @notice Stores issuance information and preferred currency information of the Synthetix contract. */
NatSpecMultiLine
hasIssued
function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; }
/** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 8468, 8635 ] }
12,323
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
setFeePool
function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; }
// ========== SETTERS ========== */
LineComment
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 2759, 2890 ] }
12,324
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
addSynth
function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; }
/** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 3960, 4389 ] }
12,325
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
removeSynth
function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. }
/** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 4535, 6049 ] }
12,326
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
effectiveValue
function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); }
/** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 6433, 6703 ] }
12,327
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
totalIssuedSynths
function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); }
/** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 6865, 7858 ] }
12,328
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
availableCurrencyKeys
function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; }
/** * @notice Returns the currencyKeys of availableSynths for rate checking */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 7953, 8304 ] }
12,329
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
availableSynthCount
function availableSynthCount() public view returns (uint) { return availableSynths.length; }
/** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 8435, 8571 ] }
12,330
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
feeRateForExchange
function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); }
/** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 8693, 9561 ] }
12,331
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
transfer
function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; }
/** * @notice ERC20 transfer function. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 9671, 10138 ] }
12,332
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
transferFrom
function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); }
/** * @notice ERC20 transferFrom function. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 10201, 10689 ] }
12,333
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
exchange
function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } }
/** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 11140, 12208 ] }
12,334
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
validateGasPrice
function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); }
/* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */
Comment
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 12358, 12523 ] }
12,335
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
synthInitiatedExchange
function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); }
/** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 13180, 13907 ] }
12,336
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
_internalExchange
function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; }
/** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 14544, 16596 ] }
12,337
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
_addToDebtRegister
function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } }
/** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 16945, 19145 ] }
12,338
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
issueSynths
function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); }
/** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 19402, 20030 ] }
12,339
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
issueMaxSynths
function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); }
/** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 20206, 20799 ] }
12,340
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
burnSynths
function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); }
/** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 20992, 22267 ] }
12,341
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
_appendAccountIssuanceRecord
function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); }
/** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 22519, 22893 ] }
12,342
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
_removeFromDebtRegister
function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); }
/** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 23127, 25213 ] }
12,343
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
maxIssuableSynths
function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); }
/** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 25501, 26038 ] }
12,344
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
collateralisationRatio
function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); }
/** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 26697, 27040 ] }
12,345
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
debtBalanceOf
function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); }
/** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 27440, 28830 ] }
12,346
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
remainingIssuableSynths
function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } }
/** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 29064, 29563 ] }
12,347
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
collateral
function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; }
/** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 29836, 30248 ] }
12,348
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
transferableSynthetix
function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } }
/** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 30513, 31650 ] }
12,349
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synthetix
contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes32 => Synth) public synths; mapping(address => bytes32) public synthsByAddress; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; IRewardsDistribution public rewardsDistribution; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; uint public gasPriceLimit; address public gasLimitOracle; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _proxy The main token address of the Proxy contract. This will be ProxyERC20.sol * @param _tokenState Address of the external immutable contract containing token balances. * @param _synthetixState External immutable contract containing the SNX minters debt ledger. * @param _owner The owner of this contract. * @param _exchangeRates External immutable contract where the price oracle pushes prices onchain too. * @param _feePool External upgradable contract handling SNX Fees and Rewards claiming * @param _supplySchedule External immutable contract with the SNX inflationary supply schedule * @param _rewardEscrow External immutable contract for SNX Rewards Escrow * @param _escrow External immutable contract for SNX Token Sale Escrow * @param _rewardsDistribution External immutable contract managing the Rewards Distribution of the SNX inflationary supply * @param _totalSupply On upgrading set to reestablish the current total supply (This should be in SynthetixState if ever updated) */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, IRewardsDistribution _rewardsDistribution, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; rewardsDistribution = _rewardsDistribution; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function setGasLimitOracle(address _gasLimitOracle) external optionalProxy_onlyOwner { gasLimitOracle = _gasLimitOracle; } function setGasPriceLimit(uint _gasPriceLimit) external { require(msg.sender == gasLimitOracle, "Only gas limit oracle allowed"); require(_gasPriceLimit > 0, "Needs to be greater than 0"); gasPriceLimit = _gasPriceLimit; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); require(synthsByAddress[synth] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[synth] = currencyKey; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes32 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR" && currencyKey != "sUSD", "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synths[currencyKey]]; delete synths[currencyKey]; // Note: No event here as Synthetix contract exceeds max contract size // with these events, and it's unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes32 currencyKey) public view returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys()); require(!anyRateStale, "Rates are stale"); for (uint i = 0; i < availableSynths.length; i++) { // What's the total issued value of that synth in the destination currency? // Note: We're not using our effectiveValue function because we don't want to go get the // rate for the destination currency and check if it's stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(rates[i]); total = total.add(synthValue); } return total.divideDecimalRound(currencyRate); } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes32[]) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[availableSynths[i]]; } return currencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } /** * @notice Determine the effective fee rate for the exchange, taking into considering swing trading */ function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) public view returns (uint) { // Get the base exchange fee rate uint exchangeFeeRate = feePool.exchangeFeeRate(); uint multiplier = 1; // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD. // Note: this assumes shorts begin with 'i' and longs with 's'. if ( (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) || (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73) ) { // If so then double the exchange fee multipler multiplier = 2; } return exchangeFeeRate.mul(multiplier); } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their staked SNX amount require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Cannot transfer staked or escrowed SNX"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. return _transferFrom_byProxy(messageSender, from, to, value); } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external optionalProxy // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // verify gas price limit validateGasPrice(tx.gasprice); // If the oracle has set protectionCircuit to true then burn the synths if (protectionCircuit) { synths[sourceCurrencyKey].burn(messageSender, sourceAmount); return true; } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /* @dev validate that the given gas price is less than or equal to the gas price limit @param _gasPrice tested gas price */ function validateGasPrice(uint _givenGasPrice) public view { require(_givenGasPrice <= gasPriceLimit, "Gas price above limit"); } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external optionalProxy returns (bool) { require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed"); require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for exchange. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); // Note: We don't need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What's the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { // Get the exchange fee rate uint exchangeFeeRate = feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey); amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.recordFeePaid(xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn't changed. //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that registers new synth as they are issued. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes32 currencyKey, uint amount) internal { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { bytes32 currencyKey = "sUSD"; require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. */ function issueMaxSynths() external optionalProxy { bytes32 currencyKey = "sUSD"; // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(currencyKey, maxIssuable); // Create their synths synths[currencyKey].issue(messageSender, maxIssuable); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Burn synths to clear issued synths/free SNX. * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */ function burnSynths(uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { bytes32 currencyKey = "sUSD"; // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(existingDebt > 0, "No debt to forgive"); // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove, existingDebt); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs * @param existingDebt The existing debt (in UNIT base) of address presented in XDRs */ function _removeFromDebtRegister(uint amount, uint existingDebt) internal { uint debtToRemove = amount; // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes32 currencyKey) public view // We don't need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, * e.g. based on an issuance ratio of 20%. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they're able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes32 currencyKey) public view // Don't need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What's the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes32 currencyKey) public view // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred for an account. * @dev Escrowed SNX are not transferable, so they are not included * in this calculation. * @notice SNX rate not stale is checked within debtBalanceOf */ function transferableSynthetix(address account) public view rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths returns (uint) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } /** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */ function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; } // ========== MODIFIERS ========== modifier rateNotStale(bytes32 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or not a synth"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only oracle allowed"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes32,uint256,bytes32,uint256,address)"); function emitSynthExchange(address account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ }
/** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */
NatSpecMultiLine
mint
function mint() external returns (bool) { require(rewardsDistribution != address(0), "RewardsDistribution not set"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); // record minting event before mutation to token supply supplySchedule.recordMintEvent(supplyToMint); // Set minted SNX balance to RewardEscrow's balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); // Get the remainder uint amountToDistribute = supplyToMint.sub(minterReward); // Set the token balance to the RewardsDistribution contract tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute)); emitTransfer(this, rewardsDistribution, amountToDistribute); // Kick off the distribution of rewards rewardsDistribution.distributeRewards(amountToDistribute); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); return true; }
/** * @notice Mints the inflationary SNX supply. The inflation shedule is * defined in the SupplySchedule contract. * The mint() function is publicly callable by anyone. The caller will receive a minter reward as specified in supplySchedule.minterReward(). */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 31941, 33267 ] }
12,350
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
MerkleProof
library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } }
/** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */
NatSpecMultiLine
verify
function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; }
/** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 357, 552 ] }
12,351
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
MerkleProof
library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } }
/** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */
NatSpecMultiLine
processProof
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; }
/** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 909, 1615 ] }
12,352
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
Strings
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. */ }
toString
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` decimal representation. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 184, 912 ] }
12,353
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
Ownable
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() external 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) external virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
/** * @dev 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. */
NatSpecMultiLine
owner
function owner() public view virtual returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 408, 500 ] }
12,354
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
Ownable
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() external 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) external virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
/** * @dev 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. */
NatSpecMultiLine
renounceOwnership
function renounceOwnership() external virtual onlyOwner { _transferOwnership(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. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 1059, 1169 ] }
12,355
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
Ownable
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() external 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) external virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
/** * @dev 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. */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) external 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`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 1319, 1527 ] }
12,356
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
Ownable
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() external 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) external virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
/** * @dev 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. */
NatSpecMultiLine
_transferOwnership
function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 1682, 1878 ] }
12,357
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
isContract
function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; }
/** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 1004, 1335 ] }
12,358
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721Receiver
interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); }
/** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */
NatSpecMultiLine
onERC721Received
function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4);
/** * @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`. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 528, 698 ] }
12,359
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC165
interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
/** * @dev 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}. */
NatSpecMultiLine
supportsInterface
function supportsInterface(bytes4 interfaceId) external view returns (bool);
/** * @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. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 374, 455 ] }
12,360
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC165
abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
/** * @dev Implementation of 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. */
NatSpecMultiLine
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; }
/** * @dev See {IERC165-supportsInterface}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 103, 265 ] }
12,361
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721
interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
/** * @dev Required interface of an ERC721 compliant contract. */
NatSpecMultiLine
balanceOf
function balanceOf(address owner) external view returns (uint256 balance);
/** * @dev Returns the number of tokens in ``owner``'s account. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 719, 798 ] }
12,362
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721
interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
/** * @dev Required interface of an ERC721 compliant contract. */
NatSpecMultiLine
ownerOf
function ownerOf(uint256 tokenId) external view returns (address owner);
/** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 944, 1021 ] }
12,363
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721
interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
/** * @dev Required interface of an ERC721 compliant contract. */
NatSpecMultiLine
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId ) external;
/** * @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. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 1733, 1850 ] }
12,364
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721
interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
/** * @dev Required interface of an ERC721 compliant contract. */
NatSpecMultiLine
transferFrom
function transferFrom( 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. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 2376, 2489 ] }
12,365
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721
interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
/** * @dev Required interface of an ERC721 compliant contract. */
NatSpecMultiLine
approve
function approve(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. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 2962, 3022 ] }
12,366
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721
interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
/** * @dev Required interface of an ERC721 compliant contract. */
NatSpecMultiLine
getApproved
function getApproved(uint256 tokenId) external view returns (address operator);
/** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 3176, 3260 ] }
12,367
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721
interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
/** * @dev Required interface of an ERC721 compliant contract. */
NatSpecMultiLine
setApprovalForAll
function setApprovalForAll(address operator, bool _approved) external;
/** * @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. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 3587, 3662 ] }
12,368
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721
interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
/** * @dev Required interface of an ERC721 compliant contract. */
NatSpecMultiLine
isApprovedForAll
function isApprovedForAll(address owner, address operator) external view returns (bool);
/** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 3813, 3906 ] }
12,369
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721
interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
/** * @dev Required interface of an ERC721 compliant contract. */
NatSpecMultiLine
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external;
/** * @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. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 4483, 4630 ] }
12,370
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721Enumerable
interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
/** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */
NatSpecMultiLine
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the total amount of tokens stored by the contract. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 132, 192 ] }
12,371
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721Enumerable
interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
/** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */
NatSpecMultiLine
tokenOfOwnerByIndex
function tokenOfOwnerByIndex(address owner, uint256 index) 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. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 375, 471 ] }
12,372
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721Enumerable
interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
/** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */
NatSpecMultiLine
tokenByIndex
function tokenByIndex(uint256 index) external view returns (uint256);
/** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 647, 721 ] }
12,373
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721Metadata
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); }
/** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */
NatSpecMultiLine
name
function name() external view returns (string memory);
/** * @dev Returns the token collection name. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 106, 165 ] }
12,374
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721Metadata
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); }
/** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */
NatSpecMultiLine
symbol
function symbol() external view returns (string memory);
/** * @dev Returns the token collection symbol. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 236, 297 ] }
12,375
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
IERC721Metadata
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); }
/** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */
NatSpecMultiLine
tokenURI
function tokenURI(uint256 tokenId) external view returns (string memory);
/** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 398, 476 ] }
12,376
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
totalSupply
function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } }
/** * @dev See {IERC721Enumerable-totalSupply}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 2044, 2329 ] }
12,377
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
tokenByIndex
function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); }
/** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 2617, 3337 ] }
12,378
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
tokenOfOwnerByIndex
function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); }
/** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 3632, 4744 ] }
12,379
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); }
/** * @dev See {IERC165-supportsInterface}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 4811, 5188 ] }
12,380
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
balanceOf
function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); }
/** * @dev See {IERC721-balanceOf}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 5247, 5458 ] }
12,381
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
ownershipOf
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); }
/** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 6085, 7173 ] }
12,382
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
ownerOf
function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; }
/** * @dev See {IERC721-ownerOf}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 7230, 7359 ] }
12,383
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
name
function name() public view virtual override returns (string memory) { return _name; }
/** * @dev See {IERC721Metadata-name}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 7421, 7526 ] }
12,384
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
symbol
function symbol() public view virtual override returns (string memory) { return _symbol; }
/** * @dev See {IERC721Metadata-symbol}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 7590, 7699 ] }
12,385
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
tokenURI
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; }
/** * @dev See {IERC721Metadata-tokenURI}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 7765, 8088 ] }
12,386
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
_baseURI
function _baseURI() internal view virtual returns (string memory) { return ''; }
/** * @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. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 8331, 8430 ] }
12,387
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
approve
function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); }
/** * @dev See {IERC721-approve}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 8487, 8863 ] }
12,388
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
getApproved
function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; }
/** * @dev See {IERC721-getApproved}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 8924, 9133 ] }
12,389
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
setApprovalForAll
function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); }
/** * @dev See {IERC721-setApprovalForAll}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 9200, 9484 ] }
12,390
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
isApprovedForAll
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; }
/** * @dev See {IERC721-isApprovedForAll}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 9550, 9719 ] }
12,391
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
transferFrom
function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); }
/** * @dev See {IERC721-transferFrom}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 9781, 9956 ] }
12,392
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); }
/** * @dev See {IERC721-safeTransferFrom}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 10022, 10212 ] }
12,393
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } }
/** * @dev See {IERC721-safeTransferFrom}. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 10278, 10625 ] }
12,394
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
_exists
function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; }
/** * @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`), */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 10875, 11024 ] }
12,395
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
_safeMint
function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); }
/** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 11494, 11662 ] }
12,396
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
_mint
function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); }
/** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 11916, 13343 ] }
12,397
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
_transfer
function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); }
/** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 13592, 15709 ] }
12,398
CryptoYachts
CryptoYachts.sol
0x7a772afba91b5569fa62a096ff20c257b9457daa
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) external view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */
NatSpecMultiLine
_burn
function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } }
/** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
MIT
ipfs://cd0f73459f488c48eb443b83685f80164f3e24a76f476670246180ce023c3f1d
{ "func_code_index": [ 15933, 17978 ] }
12,399