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
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
name
function name() external pure returns (string memory);
/** * @dev Allows users to access the token's name */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 4702, 4761 ] }
10,900
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
symbol
function symbol() external pure returns (string memory);
/** * @dev Allows users to access the token's symbol */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 4837, 4898 ] }
10,901
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
decimals
function decimals() external pure returns (uint8);
/** * @dev Allows users to access the number of decimals */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 4978, 5033 ] }
10,902
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getNewCurrentVariables
function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip );
/** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 5238, 5476 ] }
10,903
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getTopRequestIDs
function getTopRequestIDs() external view returns (uint256[5] memory _requestIds);
/** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 5597, 5711 ] }
10,904
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getNewVariablesOnDeck
function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck);
/** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 5857, 6004 ] }
10,905
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
updateTellor
function updateTellor(uint256 _disputeId) external;
/** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 6215, 6271 ] }
10,906
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
unlockDisputeFee
function unlockDisputeFee(uint256 _disputeId) external;
/** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 6392, 6452 ] }
10,907
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
allowance
function allowance(address _user, address _spender) external view returns (uint256);
/** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 6631, 6747 ] }
10,908
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
allowedToTrade
function allowedToTrade(address _user, uint256 _amount) external view returns (bool);
/** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 7006, 7123 ] }
10,909
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
balanceOf
function balanceOf(address _user) external view returns (uint256);
/** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 7331, 7402 ] }
10,910
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
balanceOfAt
function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256);
/** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 7683, 7805 ] }
10,911
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
didMine
function didMine(bytes32 _challenge, address _miner) external view returns (bool);
/** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 8118, 8232 ] }
10,912
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
didVote
function didVote(uint256 _disputeId, address _address) external view returns (bool);
/** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 8435, 8551 ] }
10,913
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getAddressVars
function getAddressVars(bytes32 _data) external view returns (address);
/** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 8931, 9007 ] }
10,914
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getAllDisputeVars
function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 );
/** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 9758, 10069 ] }
10,915
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getCurrentVariables
function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 );
/** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 10356, 10591 ] }
10,916
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getDisputeIdByDisputeHash
function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256);
/** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 10793, 10907 ] }
10,917
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getDisputeUintVars
function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256);
/** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 11408, 11535 ] }
10,918
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getLastNewValue
function getLastNewValue() external view returns (uint256, bool);
/** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 11752, 11822 ] }
10,919
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getLastNewValueById
function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool);
/** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 12070, 12189 ] }
10,920
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getMinedBlockNum
function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256);
/** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 12431, 12561 ] }
10,921
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getMinersByRequestIdAndTimestamp
function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory);
/** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 12814, 12968 ] }
10,922
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getNewValueCountbyRequestId
function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256);
/** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 13339, 13460 ] }
10,923
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getRequestIdByRequestQIndex
function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256);
/** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 13633, 13750 ] }
10,924
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getRequestIdByTimestamp
function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256);
/** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 13913, 14030 ] }
10,925
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getRequestIdByQueryHash
function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256);
/** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 14252, 14367 ] }
10,926
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getRequestQ
function getRequestQ() external view returns (uint256[51] memory);
/** * @dev Getter function for the requestQ array * @return the requestQ arrray */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 14476, 14547 ] }
10,927
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getRequestUintVars
function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256);
/** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 15127, 15254 ] }
10,928
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getRequestVars
function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 );
/** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 15683, 15937 ] }
10,929
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getStakerInfo
function getStakerInfo(address _staker) external view returns (uint256, uint256);
/** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 16185, 16298 ] }
10,930
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getSubmissionsByTimestamp
function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory);
/** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 16594, 16743 ] }
10,931
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getTimestampbyRequestIDandIndex
function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256);
/** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 16968, 17109 ] }
10,932
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getUintVar
function getUintVar(bytes32 _data) external view returns (uint256);
/** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 17690, 17762 ] }
10,933
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
getVariablesOnDeck
function getVariablesOnDeck() external view returns ( uint256, uint256, string memory );
/** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 18003, 18171 ] }
10,934
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
isInDispute
function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool);
/** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 18450, 18572 ] }
10,935
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
retrieveData
function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256);
/** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 18794, 18920 ] }
10,936
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITellor
interface ITellor { /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex ) external; /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external; /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external; /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external; /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query * */ function submitMiningSolution( string calldata _nonce, uint256 _requestId, uint256 _value ) external; /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution( string calldata _nonce, uint256[5] calldata _requestId, uint256[5] calldata _value ) external; /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external; /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external; /** * @dev This function allows miners to deposit their stake. */ function depositStake() external; /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external; /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external; /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool); /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool); /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) external returns (bool); /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory); /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory); /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8); /** * @dev Getter for the current variables that include the 5 requests Id's * @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns ( bytes32 _challenge, uint256[5] memory _requestIds, uint256 _difficutly, uint256 _tip ); /** * @dev Getter for the top tipped 5 requests Id's * @return _requestIds the 5 requestsId */ function getTopRequestIDs() external view returns (uint256[5] memory _requestIds); /** * @dev Getter for the 5 requests Id's next in line to get mined * @return idsOnDeck tipsOnDeck the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint256 _disputeId) external; /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee(uint256 _disputeId) external; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint256); /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user, uint256 _amount) external view returns (bool); /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint256); /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns (bool); /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint256 _disputeId, address _address) external view returns (bool); /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * return address */ function getAddressVars(bytes32 _data) external view returns (address); /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * uint of requestId * uint of timestamp * uint of value * uint of minExecutionDate * uint of numberOfVotes * uint of blocknumber * uint of minerSlot * uint of quorum * uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint256 _disputeId) external view returns ( bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256 ); /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns ( bytes32, uint256, uint256, string memory, uint256, uint256 ); /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256); /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns (uint256, bool); /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp( uint256 _requestId, uint256 _timestamp ) external view returns (address[5] memory); /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256); /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256); /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns (uint256); /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() external view returns (uint256[51] memory); /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256); /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint256 _requestId) external view returns ( string memory, string memory, bytes32, uint256, uint256, uint256 ); /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns (uint256, uint256); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory); /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) external view returns (uint256); /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns ( uint256, uint256, string memory ); /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool); /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint256); }
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 19033, 19093 ] }
10,937
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
LiquityMath
library LiquityMath { using SafeMath for uint; uint internal constant DECIMAL_PRECISION = 1e18; /* Precision for Nominal ICR (independent of price). Rationale for the value: * * - Making it “too high” could lead to overflows. * - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division. * * This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39 ETH, * and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator. * */ uint internal constant NICR_PRECISION = 1e20; function _min(uint _a, uint _b) internal pure returns (uint) { return (_a < _b) ? _a : _b; } function _max(uint _a, uint _b) internal pure returns (uint) { return (_a >= _b) ? _a : _b; } /* * Multiply two decimal numbers and use normal rounding rules: * -round product up if 19'th mantissa digit >= 5 * -round product down if 19'th mantissa digit < 5 * * Used only inside the exponentiation, _decPow(). */ function decMul(uint x, uint y) internal pure returns (uint decProd) { uint prod_xy = x.mul(y); decProd = prod_xy.add(DECIMAL_PRECISION / 2).div(DECIMAL_PRECISION); } /* * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n. * * Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity. * * Called by two functions that represent time in units of minutes: * 1) TroveManager._calcDecayedBaseRate * 2) CommunityIssuance._getCumulativeIssuanceFraction * * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals * "minutes in 1000 years": 60 * 24 * 365 * 1000 * * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be * negligibly different from just passing the cap, since: * * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible */ function _decPow(uint _base, uint _minutes) internal pure returns (uint) { if (_minutes > 525600000) {_minutes = 525600000;} // cap to avoid overflow if (_minutes == 0) {return DECIMAL_PRECISION;} uint y = DECIMAL_PRECISION; uint x = _base; uint n = _minutes; // Exponentiation-by-squaring while (n > 1) { if (n % 2 == 0) { x = decMul(x, x); n = n.div(2); } else { // if (n % 2 != 0) y = decMul(x, y); x = decMul(x, x); n = (n.sub(1)).div(2); } } return decMul(x, y); } function _getAbsoluteDifference(uint _a, uint _b) internal pure returns (uint) { return (_a >= _b) ? _a.sub(_b) : _b.sub(_a); } function _computeNominalCR(uint _coll, uint _debt) internal pure returns (uint) { if (_debt > 0) { return _coll.mul(NICR_PRECISION).div(_debt); } // Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR. else { // if (_debt == 0) return 2**256 - 1; } } function _computeCR(uint _coll, uint _debt, uint _price) internal pure returns (uint) { if (_debt > 0) { uint newCollRatio = _coll.mul(_price).div(_debt); return newCollRatio; } // Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR. else { // if (_debt == 0) return 2**256 - 1; } } }
decMul
function decMul(uint x, uint y) internal pure returns (uint decProd) { uint prod_xy = x.mul(y); decProd = prod_xy.add(DECIMAL_PRECISION / 2).div(DECIMAL_PRECISION); }
/* * Multiply two decimal numbers and use normal rounding rules: * -round product up if 19'th mantissa digit >= 5 * -round product down if 19'th mantissa digit < 5 * * Used only inside the exponentiation, _decPow(). */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 1145, 1341 ] }
10,938
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
LiquityMath
library LiquityMath { using SafeMath for uint; uint internal constant DECIMAL_PRECISION = 1e18; /* Precision for Nominal ICR (independent of price). Rationale for the value: * * - Making it “too high” could lead to overflows. * - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division. * * This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39 ETH, * and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator. * */ uint internal constant NICR_PRECISION = 1e20; function _min(uint _a, uint _b) internal pure returns (uint) { return (_a < _b) ? _a : _b; } function _max(uint _a, uint _b) internal pure returns (uint) { return (_a >= _b) ? _a : _b; } /* * Multiply two decimal numbers and use normal rounding rules: * -round product up if 19'th mantissa digit >= 5 * -round product down if 19'th mantissa digit < 5 * * Used only inside the exponentiation, _decPow(). */ function decMul(uint x, uint y) internal pure returns (uint decProd) { uint prod_xy = x.mul(y); decProd = prod_xy.add(DECIMAL_PRECISION / 2).div(DECIMAL_PRECISION); } /* * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n. * * Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity. * * Called by two functions that represent time in units of minutes: * 1) TroveManager._calcDecayedBaseRate * 2) CommunityIssuance._getCumulativeIssuanceFraction * * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals * "minutes in 1000 years": 60 * 24 * 365 * 1000 * * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be * negligibly different from just passing the cap, since: * * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible */ function _decPow(uint _base, uint _minutes) internal pure returns (uint) { if (_minutes > 525600000) {_minutes = 525600000;} // cap to avoid overflow if (_minutes == 0) {return DECIMAL_PRECISION;} uint y = DECIMAL_PRECISION; uint x = _base; uint n = _minutes; // Exponentiation-by-squaring while (n > 1) { if (n % 2 == 0) { x = decMul(x, x); n = n.div(2); } else { // if (n % 2 != 0) y = decMul(x, y); x = decMul(x, x); n = (n.sub(1)).div(2); } } return decMul(x, y); } function _getAbsoluteDifference(uint _a, uint _b) internal pure returns (uint) { return (_a >= _b) ? _a.sub(_b) : _b.sub(_a); } function _computeNominalCR(uint _coll, uint _debt) internal pure returns (uint) { if (_debt > 0) { return _coll.mul(NICR_PRECISION).div(_debt); } // Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR. else { // if (_debt == 0) return 2**256 - 1; } } function _computeCR(uint _coll, uint _debt, uint _price) internal pure returns (uint) { if (_debt > 0) { uint newCollRatio = _coll.mul(_price).div(_debt); return newCollRatio; } // Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR. else { // if (_debt == 0) return 2**256 - 1; } } }
_decPow
function _decPow(uint _base, uint _minutes) internal pure returns (uint) { if (_minutes > 525600000) {_minutes = 525600000;} // cap to avoid overflow if (_minutes == 0) {return DECIMAL_PRECISION;} uint y = DECIMAL_PRECISION; uint x = _base; uint n = _minutes; // Exponentiation-by-squaring while (n > 1) { if (n % 2 == 0) { x = decMul(x, x); n = n.div(2); } else { // if (n % 2 != 0) y = decMul(x, y); x = decMul(x, x); n = (n.sub(1)).div(2); } } return decMul(x, y);
/* * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n. * * Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity. * * Called by two functions that represent time in units of minutes: * 1) TroveManager._calcDecayedBaseRate * 2) CommunityIssuance._getCumulativeIssuanceFraction * * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals * "minutes in 1000 years": 60 * 24 * 365 * 1000 * * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be * negligibly different from just passing the cap, since: * * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 2280, 2984 ] }
10,939
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
Ownable
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. * * NOTE: This function is not safe, as it doesn’t check owner is calling it. * Make sure you check it before calling it. */ function _renounceOwnership() internal { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } }
owner
function owner() public view returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 445, 529 ] }
10,940
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
Ownable
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. * * NOTE: This function is not safe, as it doesn’t check owner is calling it. * Make sure you check it before calling it. */ function _renounceOwnership() internal { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } }
isOwner
function isOwner() public view returns (bool) { return msg.sender == _owner; }
/** * @dev Returns true if the caller is the current owner. */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 811, 908 ] }
10,941
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
Ownable
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. * * NOTE: This function is not safe, as it doesn’t check owner is calling it. * Make sure you check it before calling it. */ function _renounceOwnership() internal { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } }
_renounceOwnership
function _renounceOwnership() internal { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
/** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. * * NOTE: This function is not safe, as it doesn’t check owner is calling it. * Make sure you check it before calling it. */
NatSpecMultiLine
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 1353, 1491 ] }
10,942
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IBorrowerOperations
interface IBorrowerOperations { // --- Events --- event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _activePoolAddress); event DefaultPoolAddressChanged(address _defaultPoolAddress); event StabilityPoolAddressChanged(address _stabilityPoolAddress); event GasPoolAddressChanged(address _gasPoolAddress); event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event SortedTrovesAddressChanged(address _sortedTrovesAddress); event RUBCAddressChanged(address _rubcAddress); event RBSTStakingAddressChanged(address _rbstStakingAddress); event TroveCreated(address indexed _borrower, uint arrayIndex); event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation); event RUBCBorrowingFeePaid(address indexed _borrower, uint _RUBCFee); // --- Functions --- function setAddresses( address _troveManagerAddress, address _activePoolAddress, address _defaultPoolAddress, address _stabilityPoolAddress, address _gasPoolAddress, address _collSurplusPoolAddress, address _priceFeedAddress, address _sortedTrovesAddress, address _rubcAddress, address _rbstStakingAddress ) external; function openTrove(uint _maxFee, uint _RUBCAmount, address _upperHint, address _lowerHint) external payable; function addColl(address _upperHint, address _lowerHint) external payable; function moveETHGainToTrove(address _user, address _upperHint, address _lowerHint) external payable; function withdrawColl(uint _amount, address _upperHint, address _lowerHint) external; function withdrawRUBC(uint _maxFee, uint _amount, address _upperHint, address _lowerHint) external; function repayRUBC(uint _amount, address _upperHint, address _lowerHint) external; function closeTrove() external; function adjustTrove(uint _maxFee, uint _collWithdrawal, uint _debtChange, bool isDebtIncrease, address _upperHint, address _lowerHint) external payable; function claimCollateral() external; function getCompositeDebt(uint _debt) external pure returns (uint); }
setAddresses
function setAddresses( address _troveManagerAddress, address _activePoolAddress, address _defaultPoolAddress, address _stabilityPoolAddress, address _gasPoolAddress, address _collSurplusPoolAddress, address _priceFeedAddress, address _sortedTrovesAddress, address _rubcAddress, address _rbstStakingAddress ) external;
// --- Functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 1006, 1423 ] }
10,943
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ICollSurplusPool
interface ICollSurplusPool { // --- Events --- event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event CollBalanceUpdated(address indexed _account, uint _newBalance); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress ) external; function getETH() external view returns (uint); function getCollateral(address _account) external view returns (uint); function accountSurplus(address _account, uint _amount) external; function claimColl(address _account) external; }
setAddresses
function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress ) external;
// --- Contract setters ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 448, 612 ] }
10,944
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ICommunityIssuance
interface ICommunityIssuance { // --- Events --- event RBSTAddressSet(address _rbstAddress); event StabilityPoolAddressSet(address _stabilityPoolAddress); event TotalRBSTIssuedUpdated(uint _totalRBSTIssued); // --- Functions --- function setAddresses(address _rbstAddress, address _stabilityPoolAddress) external; function issueRBST() external returns (uint); function sendRBST(address _account, uint _RBSTamount) external; }
setAddresses
function setAddresses(address _rbstAddress, address _stabilityPoolAddress) external;
// --- Functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 272, 361 ] }
10,945
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ILockupContractFactory
interface ILockupContractFactory { // --- Events --- event RBSTAddressSet(address _rbstAddress); event LockupContractDeployedThroughFactory(address _lockupContractAddress, address _beneficiary, uint _unlockTime, address _deployer); // --- Functions --- function setRBSTAddress(address _rbstAddress) external; function deployLockupContract(address _beneficiary, uint _unlockTime) external; function isRegisteredLockup(address _addr) external view returns (bool); }
setRBSTAddress
function setRBSTAddress(address _rbstAddress) external;
// --- Functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 286, 346 ] }
10,946
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IPool
interface IPool { // --- Events --- event ETHBalanceUpdated(uint _newBalance); event RUBCBalanceUpdated(uint _newBalance); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event StabilityPoolAddressChanged(address _newStabilityPoolAddress); event EtherSent(address _to, uint _amount); // --- Functions --- function getETH() external view returns (uint); function getRUBCDebt() external view returns (uint); function increaseRUBCDebt(uint _amount) external; function decreaseRUBCDebt(uint _amount) external; }
// Common interface for the Pools.
LineComment
getETH
function getETH() external view returns (uint);
// --- Functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 446, 498 ] }
10,947
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IPriceFeed
interface IPriceFeed { // --- Events --- event LastGoodPriceUpdated(uint _lastGoodPrice); // --- Function --- function fetchPrice() external returns (uint); function fetchRUBPriceFeedUpdateTimestamp() external returns(uint256); }
fetchPrice
function fetchPrice() external returns (uint);
// --- Function ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 133, 184 ] }
10,948
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IRBST
interface IRBST is IERC20, IERC2612 { // --- Events --- event CommunityIssuanceAddressSet(address _communityIssuanceAddress); event RBSTStakingAddressSet(address _rbstStakingAddress); event LockupContractFactoryAddressSet(address _lockupContractFactoryAddress); // --- Functions --- function sendToRBSTStaking(address _sender, uint256 _amount) external; function getDeploymentStartTime() external view returns (uint256); function getLpRewardsEntitlement() external view returns (uint256); }
sendToRBSTStaking
function sendToRBSTStaking(address _sender, uint256 _amount) external;
// --- Functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 329, 404 ] }
10,949
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IRBSTStaking
interface IRBSTStaking { // --- Events -- event RBSTAddressSet(address _rbstAddress); event RUBCAddressSet(address _rubcAddress); event TroveManagerAddressSet(address _troveManager); event BorrowerOperationsAddressSet(address _borrowerOperationsAddress); event ActivePoolAddressSet(address _activePoolAddress); event StakeChanged(address indexed staker, uint newStake); event StakingGainsWithdrawn(address indexed staker, uint RUBCGain, uint ETHGain); event F_ETHUpdated(uint _F_ETH); event F_RUBCUpdated(uint _F_RUBC); event TotalRBSTStakedUpdated(uint _totalRBSTStaked); event EtherSent(address _account, uint _amount); event StakerSnapshotsUpdated(address _staker, uint _F_ETH, uint _F_RUBC); // --- Functions --- function setAddresses ( address _rbstAddress, address _rubcAddress, address _troveManagerAddress, address _borrowerOperationsAddress, address _activePoolAddress ) external; function stake(uint _RBSTamount) external; function unstake(uint _RBSTamount) external; function increaseF_ETH(uint _ETHFee) external; function increaseF_RUBC(uint _RBSTFee) external; function getPendingETHGain(address _user) external view returns (uint); function getPendingRUBCGain(address _user) external view returns (uint); }
setAddresses
function setAddresses ( address _rbstAddress, address _rubcAddress, address _troveManagerAddress, address _borrowerOperationsAddress, address _activePoolAddress ) external;
// --- Functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 802, 1036 ] }
10,950
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IRUBC
interface IRUBC is IERC20, IERC2612 { // --- Events --- event TroveManagerAddressChanged(address _troveManagerAddress); event StabilityPoolAddressChanged(address _newStabilityPoolAddress); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event RUBCBalanceUpdated(address _user, uint _amount); // --- Functions --- function mint(address _account, uint256 _amount) external; function burn(address _account, uint256 _amount) external; function sendToPool(address _sender, address poolAddress, uint256 _amount) external; function returnFromPool(address poolAddress, address user, uint256 _amount ) external; }
mint
function mint(address _account, uint256 _amount) external;
// --- Functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 390, 453 ] }
10,951
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ISortedTroves
interface ISortedTroves { // --- Events --- event SortedTrovesAddressChanged(address _sortedDoublyLLAddress); event BorrowerOperationsAddressChanged(address _borrowerOperationsAddress); event NodeAdded(address _id, uint _NICR); event NodeRemoved(address _id); // --- Functions --- function setParams(uint256 _size, address _TroveManagerAddress, address _borrowerOperationsAddress) external; function insert(address _id, uint256 _ICR, address _prevId, address _nextId) external; function remove(address _id) external; function reInsert(address _id, uint256 _newICR, address _prevId, address _nextId) external; function contains(address _id) external view returns (bool); function isFull() external view returns (bool); function isEmpty() external view returns (bool); function getSize() external view returns (uint256); function getMaxSize() external view returns (uint256); function getFirst() external view returns (address); function getLast() external view returns (address); function getNext(address _id) external view returns (address); function getPrev(address _id) external view returns (address); function validInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (bool); function findInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (address, address); }
setParams
function setParams(uint256 _size, address _TroveManagerAddress, address _borrowerOperationsAddress) external;
// --- Functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 328, 442 ] }
10,952
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IStabilityPool
interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalRUBCDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorRBSTGain(address _depositor) external view returns (uint); /* * Return the RBST gain earned by the front end. */ function getFrontEndRBSTGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedRUBCDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ }
setAddresses
function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external;
/* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 1990, 2304 ] }
10,953
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IStabilityPool
interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalRUBCDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorRBSTGain(address _depositor) external view returns (uint); /* * Return the RBST gain earned by the front end. */ function getFrontEndRBSTGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedRUBCDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ }
provideToSP
function provideToSP(uint _amount, address _frontEndTag) external;
/* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 2972, 3043 ] }
10,954
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IStabilityPool
interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalRUBCDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorRBSTGain(address _depositor) external view returns (uint); /* * Return the RBST gain earned by the front end. */ function getFrontEndRBSTGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedRUBCDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ }
withdrawFromSP
function withdrawFromSP(uint _amount) external;
/* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 3796, 3848 ] }
10,955
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IStabilityPool
interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalRUBCDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorRBSTGain(address _depositor) external view returns (uint); /* * Return the RBST gain earned by the front end. */ function getFrontEndRBSTGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedRUBCDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ }
withdrawETHGainToTrove
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external;
/* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 4516, 4602 ] }
10,956
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IStabilityPool
interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalRUBCDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorRBSTGain(address _depositor) external view returns (uint); /* * Return the RBST gain earned by the front end. */ function getFrontEndRBSTGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedRUBCDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ }
registerFrontEnd
function registerFrontEnd(uint _kickbackRate) external;
/* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 4877, 4937 ] }
10,957
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IStabilityPool
interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalRUBCDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorRBSTGain(address _depositor) external view returns (uint); /* * Return the RBST gain earned by the front end. */ function getFrontEndRBSTGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedRUBCDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ }
offset
function offset(uint _debt, uint _coll) external;
/* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 5284, 5338 ] }
10,958
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IStabilityPool
interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalRUBCDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorRBSTGain(address _depositor) external view returns (uint); /* * Return the RBST gain earned by the front end. */ function getFrontEndRBSTGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedRUBCDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ }
getETH
function getETH() external view returns (uint);
/* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 5542, 5594 ] }
10,959
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IStabilityPool
interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalRUBCDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorRBSTGain(address _depositor) external view returns (uint); /* * Return the RBST gain earned by the front end. */ function getFrontEndRBSTGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedRUBCDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ }
getTotalRUBCDeposits
function getTotalRUBCDeposits() external view returns (uint);
/* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 5721, 5787 ] }
10,960
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IStabilityPool
interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalRUBCDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorRBSTGain(address _depositor) external view returns (uint); /* * Return the RBST gain earned by the front end. */ function getFrontEndRBSTGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedRUBCDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ }
getDepositorETHGain
function getDepositorETHGain(address _depositor) external view returns (uint);
/* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 5898, 5981 ] }
10,961
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IStabilityPool
interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalRUBCDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorRBSTGain(address _depositor) external view returns (uint); /* * Return the RBST gain earned by the front end. */ function getFrontEndRBSTGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedRUBCDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ }
getDepositorRBSTGain
function getDepositorRBSTGain(address _depositor) external view returns (uint);
/* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 6343, 6427 ] }
10,962
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IStabilityPool
interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalRUBCDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorRBSTGain(address _depositor) external view returns (uint); /* * Return the RBST gain earned by the front end. */ function getFrontEndRBSTGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedRUBCDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ }
getFrontEndRBSTGain
function getFrontEndRBSTGain(address _frontEnd) external view returns (uint);
/* * Return the RBST gain earned by the front end. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 6501, 6583 ] }
10,963
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IStabilityPool
interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalRUBCDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorRBSTGain(address _depositor) external view returns (uint); /* * Return the RBST gain earned by the front end. */ function getFrontEndRBSTGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedRUBCDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ }
getCompoundedRUBCDeposit
function getCompoundedRUBCDeposit(address _depositor) external view returns (uint);
/* * Return the user's compounded deposit. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 6649, 6737 ] }
10,964
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IStabilityPool
interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalRUBCDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorRBSTGain(address _depositor) external view returns (uint); /* * Return the RBST gain earned by the front end. */ function getFrontEndRBSTGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedRUBCDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ }
getCompoundedFrontEndStake
function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint);
/* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 6915, 7004 ] }
10,965
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
TellorCaller
contract TellorCaller is ITellorCaller { using SafeMath for uint256; ITellor public tellor; constructor (address _tellorMasterAddress) public { tellor = ITellor(_tellorMasterAddress); } /* * getTellorCurrentValue(): identical to getCurrentValue() in UsingTellor.sol * * @dev Allows the user to get the latest value for the requestId specified * @param _requestId is the requestId to look up the value for * @return ifRetrieve bool true if it is able to retrieve a value, the value, and the value's timestamp * @return value the value retrieved * @return _timestampRetrieved the value's timestamp */ function getTellorCurrentValue(uint256 _requestId) external view override returns ( bool ifRetrieve, uint256 value, uint256 _timestampRetrieved ) { uint256 _count = tellor.getNewValueCountbyRequestId(_requestId); uint256 _time = tellor.getTimestampbyRequestIDandIndex(_requestId, _count.sub(1)); uint256 _value = tellor.retrieveData(_requestId, _time); if (_value > 0) return (true, _value, _time); return (false, 0, _time); } }
getTellorCurrentValue
function getTellorCurrentValue(uint256 _requestId) external view override returns ( bool ifRetrieve, uint256 value, uint256 _timestampRetrieved ) { uint256 _count = tellor.getNewValueCountbyRequestId(_requestId); uint256 _time = tellor.getTimestampbyRequestIDandIndex(_requestId, _count.sub(1)); uint256 _value = tellor.retrieveData(_requestId, _time); if (_value > 0) return (true, _value, _time); return (false, 0, _time); }
/* * getTellorCurrentValue(): identical to getCurrentValue() in UsingTellor.sol * * @dev Allows the user to get the latest value for the requestId specified * @param _requestId is the requestId to look up the value for * @return ifRetrieve bool true if it is able to retrieve a value, the value, and the value's timestamp * @return value the value retrieved * @return _timestampRetrieved the value's timestamp */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 680, 1263 ] }
10,966
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IActivePool
interface IActivePool is IPool { // --- Events --- event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolRUBCDebtUpdated(uint _RUBCDebt); event ActivePoolETHBalanceUpdated(uint _ETH); // --- Functions --- function sendETH(address _account, uint _amount) external; }
sendETH
function sendETH(address _account, uint _amount) external;
// --- Functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 346, 409 ] }
10,967
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
IDefaultPool
interface IDefaultPool is IPool { // --- Events --- event TroveManagerAddressChanged(address _newTroveManagerAddress); event DefaultPoolRUBCDebtUpdated(uint _RUBCDebt); event DefaultPoolETHBalanceUpdated(uint _ETH); // --- Functions --- function sendETHToActivePool(uint _amount) external; }
sendETHToActivePool
function sendETHToActivePool(uint _amount) external;
// --- Functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 265, 322 ] }
10,968
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
ITroveManager
interface ITroveManager is ILiquityBase { // --- Events --- event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event RUBCAddressChanged(address _newRUBCAddress); event ActivePoolAddressChanged(address _activePoolAddress); event DefaultPoolAddressChanged(address _defaultPoolAddress); event StabilityPoolAddressChanged(address _stabilityPoolAddress); event GasPoolAddressChanged(address _gasPoolAddress); event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress); event SortedTrovesAddressChanged(address _sortedTrovesAddress); event RBSTAddressChanged(address _rbstAddress); event RBSTStakingAddressChanged(address _rbstStakingAddress); event Liquidation(uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _RUBCGasCompensation); event Redemption(uint _attemptedRUBCAmount, uint _actualRUBCAmount, uint _ETHSent, uint _ETHFee); event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation); event TroveLiquidated(address indexed _borrower, uint _debt, uint _coll, uint8 operation); event BaseRateUpdated(uint _baseRate); event LastFeeOpTimeUpdated(uint _lastFeeOpTime); event TotalStakesUpdated(uint _newTotalStakes); event SystemSnapshotsUpdated(uint _totalStakesSnapshot, uint _totalCollateralSnapshot); event LTermsUpdated(uint _L_ETH, uint _L_RUBCDebt); event TroveSnapshotsUpdated(uint _L_ETH, uint _L_RUBCDebt); event TroveIndexUpdated(address _borrower, uint _newIndex); // --- Functions --- function setAddresses( address _borrowerOperationsAddress, address _activePoolAddress, address _defaultPoolAddress, address _stabilityPoolAddress, address _gasPoolAddress, address _collSurplusPoolAddress, address _priceFeedAddress, address _rubcAddress, address _sortedTrovesAddress, address _rbstAddress, address _rbstStakingAddress ) external; function stabilityPool() external view returns (IStabilityPool); function rubc() external view returns (IRUBC); function rbst() external view returns (IRBST); function rbstStaking() external view returns (IRBSTStaking); function getTroveOwnersCount() external view returns (uint); function getTroveFromTroveOwnersArray(uint _index) external view returns (address); function getNominalICR(address _borrower) external view returns (uint); function getCurrentICR(address _borrower, uint _price) external view returns (uint); function liquidate(address _borrower) external; function liquidateTroves(uint _n) external; function batchLiquidateTroves(address[] calldata _troveArray) external; function redeemCollateral( uint _RUBCAmount, address _firstRedemptionHint, address _upperPartialRedemptionHint, address _lowerPartialRedemptionHint, uint _partialRedemptionHintNICR, uint _maxIterations, uint _maxFee ) external; function updateStakeAndTotalStakes(address _borrower) external returns (uint); function updateTroveRewardSnapshots(address _borrower) external; function addTroveOwnerToArray(address _borrower) external returns (uint index); function applyPendingRewards(address _borrower) external; function getPendingETHReward(address _borrower) external view returns (uint); function getPendingRUBCDebtReward(address _borrower) external view returns (uint); function hasPendingRewards(address _borrower) external view returns (bool); function getEntireDebtAndColl(address _borrower) external view returns ( uint debt, uint coll, uint pendingRUBCDebtReward, uint pendingETHReward ); function closeTrove(address _borrower) external; function removeStake(address _borrower) external; function getRedemptionRate() external view returns (uint); function getRedemptionRateWithDecay() external view returns (uint); function getRedemptionFeeWithDecay(uint _ETHDrawn) external view returns (uint); function getBorrowingRate() external view returns (uint); function getBorrowingRateWithDecay() external view returns (uint); function getBorrowingFee(uint RUBCDebt) external view returns (uint); function getBorrowingFeeWithDecay(uint _RUBCDebt) external view returns (uint); function decayBaseRateFromBorrowing() external; function getTroveStatus(address _borrower) external view returns (uint); function getTroveStake(address _borrower) external view returns (uint); function getTroveDebt(address _borrower) external view returns (uint); function getTroveColl(address _borrower) external view returns (uint); function setTroveStatus(address _borrower, uint num) external; function increaseTroveColl(address _borrower, uint _collIncrease) external returns (uint); function decreaseTroveColl(address _borrower, uint _collDecrease) external returns (uint); function increaseTroveDebt(address _borrower, uint _debtIncrease) external returns (uint); function decreaseTroveDebt(address _borrower, uint _collDecrease) external returns (uint); function getTCR(uint _price) external view returns (uint); function checkRecoveryMode(uint _price) external view returns (bool); }
setAddresses
function setAddresses( address _borrowerOperationsAddress, address _activePoolAddress, address _defaultPoolAddress, address _stabilityPoolAddress, address _gasPoolAddress, address _collSurplusPoolAddress, address _priceFeedAddress, address _rubcAddress, address _sortedTrovesAddress, address _rbstAddress, address _rbstStakingAddress ) external;
// --- Functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 1695, 2149 ] }
10,969
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
LiquityBase
contract LiquityBase is BaseMath, ILiquityBase { using SafeMath for uint; uint constant public _100pct = 1000000000000000000; // 1e18 == 100% // Minimum collateral ratio for individual troves uint constant public MCR = 1100000000000000000; // 110% // Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, Recovery Mode is triggered. uint constant public CCR = 1500000000000000000; // 150% // Amount of RUBC to be locked in gas pool on opening troves uint constant public RUBC_GAS_COMPENSATION = 20_000e18; // Minimum amount of net RUBC debt a trove must have uint constant public MIN_NET_DEBT = 100_000e18; uint constant public PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5% uint constant public BORROWING_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5% IActivePool public activePool; IDefaultPool public defaultPool; IPriceFeed public override priceFeed; // --- Gas compensation functions --- // Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation function _getCompositeDebt(uint _debt) internal pure returns (uint) { return _debt.add(RUBC_GAS_COMPENSATION); } function _getNetDebt(uint _debt) internal pure returns (uint) { return _debt.sub(RUBC_GAS_COMPENSATION); } // Return the amount of ETH to be drawn from a trove's collateral and sent as gas compensation. function _getCollGasCompensation(uint _entireColl) internal pure returns (uint) { return _entireColl / PERCENT_DIVISOR; } function getEntireSystemColl() public view returns (uint entireSystemColl) { uint activeColl = activePool.getETH(); uint liquidatedColl = defaultPool.getETH(); return activeColl.add(liquidatedColl); } function getEntireSystemDebt() public view returns (uint entireSystemDebt) { uint activeDebt = activePool.getRUBCDebt(); uint closedDebt = defaultPool.getRUBCDebt(); return activeDebt.add(closedDebt); } function _getTCR(uint _price) internal view returns (uint TCR) { uint entireSystemColl = getEntireSystemColl(); uint entireSystemDebt = getEntireSystemDebt(); TCR = LiquityMath._computeCR(entireSystemColl, entireSystemDebt, _price); return TCR; } function _checkRecoveryMode(uint _price) internal view returns (bool) { uint TCR = _getTCR(_price); return TCR < CCR; } function _requireUserAcceptsFee(uint _fee, uint _amount, uint _maxFeePercentage) internal pure { uint feePercentage = _fee.mul(DECIMAL_PRECISION).div(_amount); require(feePercentage <= _maxFeePercentage, "Fee exceeded provided maximum"); } }
_getCompositeDebt
function _getCompositeDebt(uint _debt) internal pure returns (uint) { return _debt.add(RUBC_GAS_COMPENSATION); }
// --- Gas compensation functions --- // Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 1168, 1299 ] }
10,970
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
LiquityBase
contract LiquityBase is BaseMath, ILiquityBase { using SafeMath for uint; uint constant public _100pct = 1000000000000000000; // 1e18 == 100% // Minimum collateral ratio for individual troves uint constant public MCR = 1100000000000000000; // 110% // Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, Recovery Mode is triggered. uint constant public CCR = 1500000000000000000; // 150% // Amount of RUBC to be locked in gas pool on opening troves uint constant public RUBC_GAS_COMPENSATION = 20_000e18; // Minimum amount of net RUBC debt a trove must have uint constant public MIN_NET_DEBT = 100_000e18; uint constant public PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5% uint constant public BORROWING_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5% IActivePool public activePool; IDefaultPool public defaultPool; IPriceFeed public override priceFeed; // --- Gas compensation functions --- // Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation function _getCompositeDebt(uint _debt) internal pure returns (uint) { return _debt.add(RUBC_GAS_COMPENSATION); } function _getNetDebt(uint _debt) internal pure returns (uint) { return _debt.sub(RUBC_GAS_COMPENSATION); } // Return the amount of ETH to be drawn from a trove's collateral and sent as gas compensation. function _getCollGasCompensation(uint _entireColl) internal pure returns (uint) { return _entireColl / PERCENT_DIVISOR; } function getEntireSystemColl() public view returns (uint entireSystemColl) { uint activeColl = activePool.getETH(); uint liquidatedColl = defaultPool.getETH(); return activeColl.add(liquidatedColl); } function getEntireSystemDebt() public view returns (uint entireSystemDebt) { uint activeDebt = activePool.getRUBCDebt(); uint closedDebt = defaultPool.getRUBCDebt(); return activeDebt.add(closedDebt); } function _getTCR(uint _price) internal view returns (uint TCR) { uint entireSystemColl = getEntireSystemColl(); uint entireSystemDebt = getEntireSystemDebt(); TCR = LiquityMath._computeCR(entireSystemColl, entireSystemDebt, _price); return TCR; } function _checkRecoveryMode(uint _price) internal view returns (bool) { uint TCR = _getTCR(_price); return TCR < CCR; } function _requireUserAcceptsFee(uint _fee, uint _amount, uint _maxFeePercentage) internal pure { uint feePercentage = _fee.mul(DECIMAL_PRECISION).div(_amount); require(feePercentage <= _maxFeePercentage, "Fee exceeded provided maximum"); } }
_getCollGasCompensation
function _getCollGasCompensation(uint _entireColl) internal pure returns (uint) { return _entireColl / PERCENT_DIVISOR; }
// Return the amount of ETH to be drawn from a trove's collateral and sent as gas compensation.
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 1531, 1671 ] }
10,971
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
setAddresses
function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); }
// --- Contract setters ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 5480, 7075 ] }
10,972
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
getETH
function getETH() external view override returns (uint) { return ETH; }
// --- Getters for public variables. Required by IPool interface ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 7154, 7244 ] }
10,973
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
provideToSP
function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); }
/* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 7936, 9616 ] }
10,974
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
withdrawFromSP
function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); }
/* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 10224, 11903 ] }
10,975
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
withdrawETHGainToTrove
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); }
/* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 12443, 14354 ] }
10,976
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
_triggerRBSTIssuance
function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); }
// --- RBST issuance functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 14399, 14583 ] }
10,977
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
offset
function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); }
/* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 16862, 17490 ] }
10,978
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
_computeRewardsPerUnitStaked
function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); }
// --- Offset helper functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 17535, 19631 ] }
10,979
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
_updateRewardSumAndProduct
function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); }
// Update the Stability Pool reward sum S and product P
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 19695, 22099 ] }
10,980
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
getDepositorETHGain
function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; }
/* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 23223, 23611 ] }
10,981
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
getDepositorRBSTGain
function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; }
/* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 24868, 25768 ] }
10,982
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
getFrontEndRBSTGain
function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; }
/* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 26073, 26631 ] }
10,983
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
getCompoundedRUBCDeposit
function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; }
/* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 27853, 28272 ] }
10,984
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
getCompoundedFrontEndStake
function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; }
/* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */
Comment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 28646, 29067 ] }
10,985
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
_getCompoundedStakeFromSnapshots
function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; }
// Internal function, used to calculcate compounded deposits and compounded front end stakes.
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 29169, 30949 ] }
10,986
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
_sendRUBCtoStabilityPool
function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); }
// --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 31139, 31476 ] }
10,987
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
_sendRUBCToDepositor
function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); }
// Send RUBC to user and decrease RUBC in Pool
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 31937, 32189 ] }
10,988
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
registerFrontEnd
function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); }
// --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 32318, 32721 ] }
10,989
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
_setFrontEndTag
function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); }
// --- Stability Pool Deposit Functionality ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 32779, 32982 ] }
10,990
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
_requireCallerIsActivePool
function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); }
// --- 'require' functions ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 35928, 36090 ] }
10,991
StabilityPool
StabilityPool.sol
0x9a795fcb3bb0e712f0a681f7463644079eead62d
Solidity
StabilityPool
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; IRUBC public rubc; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalRUBCDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some RUBC debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate RBST gains. During it's lifetime, each deposit d_t earns a RBST gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * RBST reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the RBST reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the RBST issuance calculation uint public lastRBSTError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastRUBCLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolRUBCBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event RUBCAddressChanged(address _newRUBCAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss); event RBSTPaidToDepositor(address indexed _depositor, uint _RBST); event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalRUBCDeposits() external view override returns (uint) { return totalRUBCDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- RBST issuance functions --- function _triggerRBSTIssuance(ICommunityIssuance _communityIssuance) internal { uint RBSTIssuance = _communityIssuance.issueRBST(); _updateG(RBSTIssuance); } function _updateG(uint _RBSTIssuance) internal { uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the RBST issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalRUBC == 0 || _RBSTIssuance == 0) {return;} uint RBSTPerUnitStaked; RBSTPerUnitStaked =_computeRBSTPerUnitStaked(_RBSTIssuance, totalRUBC); uint marginalRBSTGain = RBSTPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalRBSTGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeRBSTPerUnitStaked(uint _RBSTIssuance, uint _totalRUBCDeposits) internal returns (uint) { /* * Calculate the RBST-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint RBSTNumerator = _RBSTIssuance.mul(DECIMAL_PRECISION).add(lastRBSTError); uint RBSTPerUnitStaked = RBSTNumerator.div(_totalRUBCDeposits); lastRBSTError = RBSTNumerator.sub(RBSTPerUnitStaked.mul(_totalRUBCDeposits)); return RBSTPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalRUBCDeposits ) internal returns (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) { /* * Compute the RUBC and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalRUBCDeposits); if (_debtToOffset == _totalRUBCDeposits) { RUBCLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastRUBCLossError_Offset = 0; } else { uint RUBCLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastRUBCLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" RUBC loss, * which ensures the error in any given compoundedRUBCDeposit favors the Stability Pool. */ RUBCLossPerUnitStaked = (RUBCLossNumerator.div(_totalRUBCDeposits)).add(1); lastRUBCLossError_Offset = (RUBCLossPerUnitStaked.mul(_totalRUBCDeposits)).sub(RUBCLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalRUBCDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalRUBCDeposits)); return (ETHGainPerUnitStaked, RUBCLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _RUBCLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_RUBCLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool RUBC in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - RUBCLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_RUBCLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated RUBC debt with the RUBC in the stability pool activePoolCached.decreaseRUBCDebt(_debtToOffset); _decreaseRUBC(_debtToOffset); // Burn the debt that was successfully offset rubc.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseRUBC(uint _amount) internal { uint newTotalRUBCDeposits = totalRUBCDeposits.sub(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } /* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; } function _getRBSTGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The RBST gain may span up to one scale change. * If it does, the second portion of the RBST gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint RBSTGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return RBSTGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for RUBC deposit, ETH gains and RBST gains --- // Transfer the RUBC tokens from the user to the Stability Pool's address, and update its recorded RUBC function _sendRUBCtoStabilityPool(address _address, uint _amount) internal { rubc.sendToPool(_address, address(this), _amount); uint newTotalRUBCDeposits = totalRUBCDeposits.add(_amount); totalRUBCDeposits = newTotalRUBCDeposits; emit StabilityPoolRUBCBalanceUpdated(newTotalRUBCDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send RUBC to user and decrease RUBC in Pool function _sendRUBCToDepositor(address _depositor, uint RUBCWithdrawal) internal { if (RUBCWithdrawal == 0) {return;} rubc.returnFromPool(address(this), _depositor, RUBCWithdrawal); _decreaseRUBC(RUBCWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutRBSTGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's RBST gain if (_frontEnd != address(0)) { uint frontEndRBSTGain = getFrontEndRBSTGain(_frontEnd); _communityIssuance.sendRBST(_frontEnd, frontEndRBSTGain); emit RBSTPaidToFrontEnd(_frontEnd, frontEndRBSTGain); } // Pay out depositor's RBST gain uint depositorRBSTGain = getDepositorRBSTGain(_depositor); _communityIssuance.sendRBST(_depositor, depositorRBSTGain); emit RBSTPaidToDepositor(_depositor, depositorRBSTGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } }
/* * The Stability Pool holds RUBC tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its RUBC debt gets offset with * RUBC in the Stability Pool: that is, the offset debt evaporates, and an equal amount of RUBC tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a RUBC loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total RUBC in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion RUBC has depleted to < 1 RUBC). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- RBST ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An RBST issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued RBST in proportion to the deposit as a share of total deposits. The RBST earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#rbst-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track RBST gains for depositors, where 'G' is the sum corresponding to RBST gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */
Comment
// --- Fallback function ---
LineComment
v0.6.11+commit.5ef660b1
MIT
ipfs://a734944afd5442c2495e6e339d58566052b7f55554e5cc7305e548ca14cf30f5
{ "func_code_index": [ 38287, 38447 ] }
10,992
Vault
Vault.sol
0x598ab825d607ace3b00d8714c0a141c7ae2e6822
Solidity
Owned
contract Owned { /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner { if (msg.sender != owner) throw; _; } address public owner; /// @notice The Constructor assigns the message sender to be `owner` function Owned() { owner = msg.sender;} /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner. 0x0 can be used to create /// an unowned neutral vault, however that cannot be undone function changeOwner(address _newOwner) onlyOwner { owner = _newOwner; NewOwner(msg.sender, _newOwner); } event NewOwner(address indexed oldOwner, address indexed newOwner); }
/// @title Vault Contract /// @author Jordi Baylina /// @notice This contract holds funds for Campaigns and automates payments, it /// intends to be a safe place to store funds equipped with optional variable /// time delays to allow for an optional escape hatch /// @dev `Owned` is a base level contract that assigns an `owner` that can be /// later changed
NatSpecSingleLine
Owned
function Owned() { owner = msg.sender;}
/// @notice The Constructor assigns the message sender to be `owner`
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://68cd6154297c049e19a780d0ef661705ad3182cbc26e6886b7998f84aa4cfa7b
{ "func_code_index": [ 281, 325 ] }
10,993
Vault
Vault.sol
0x598ab825d607ace3b00d8714c0a141c7ae2e6822
Solidity
Owned
contract Owned { /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner { if (msg.sender != owner) throw; _; } address public owner; /// @notice The Constructor assigns the message sender to be `owner` function Owned() { owner = msg.sender;} /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner. 0x0 can be used to create /// an unowned neutral vault, however that cannot be undone function changeOwner(address _newOwner) onlyOwner { owner = _newOwner; NewOwner(msg.sender, _newOwner); } event NewOwner(address indexed oldOwner, address indexed newOwner); }
/// @title Vault Contract /// @author Jordi Baylina /// @notice This contract holds funds for Campaigns and automates payments, it /// intends to be a safe place to store funds equipped with optional variable /// time delays to allow for an optional escape hatch /// @dev `Owned` is a base level contract that assigns an `owner` that can be /// later changed
NatSpecSingleLine
changeOwner
function changeOwner(address _newOwner) onlyOwner { owner = _newOwner; NewOwner(msg.sender, _newOwner); }
/// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner. 0x0 can be used to create /// an unowned neutral vault, however that cannot be undone
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://68cd6154297c049e19a780d0ef661705ad3182cbc26e6886b7998f84aa4cfa7b
{ "func_code_index": [ 558, 691 ] }
10,994
Vault
Vault.sol
0x598ab825d607ace3b00d8714c0a141c7ae2e6822
Solidity
Escapable
contract Escapable is Owned { address public escapeHatchCaller; address public escapeHatchDestination; /// @notice The Constructor assigns the `escapeHatchDestination` and the /// `escapeHatchCaller` /// @param _escapeHatchDestination The address of a safe location (usu a /// Multisig) to send the ether held in this contract /// @param _escapeHatchCaller The address of a trusted account or contract to /// call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal that `escapeHatchCaller` cannot move /// funds out of `escapeHatchDestination` function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) { escapeHatchCaller = _escapeHatchCaller; escapeHatchDestination = _escapeHatchDestination; } /// @dev The addresses preassigned the `escapeHatchCaller` role /// is the only addresses that can call a function with this modifier modifier onlyEscapeHatchCallerOrOwner { if ((msg.sender != escapeHatchCaller)&&(msg.sender != owner)) throw; _; } /// @notice The `escapeHatch()` should only be called as a last resort if a /// security issue is uncovered or something unexpected happened function escapeHatch() onlyEscapeHatchCallerOrOwner { uint total = this.balance; // Send the total balance of this contract to the `escapeHatchDestination` if (!escapeHatchDestination.send(total)) { throw; } EscapeHatchCalled(total); } /// @notice Changes the address assigned to call `escapeHatch()` /// @param _newEscapeHatchCaller The address of a trusted account or contract to /// call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal that `escapeHatchCaller` cannot /// move funds out of `escapeHatchDestination` function changeEscapeCaller(address _newEscapeHatchCaller) onlyEscapeHatchCallerOrOwner { escapeHatchCaller = _newEscapeHatchCaller; } event EscapeHatchCalled(uint amount); }
/// @dev `Escapable` is a base level contract built off of the `Owned` /// contract that creates an escape hatch function to send its ether to /// `escapeHatchDestination` when called by the `escapeHatchCaller` in the case that /// something unexpected happens
NatSpecSingleLine
Escapable
function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) { escapeHatchCaller = _escapeHatchCaller; escapeHatchDestination = _escapeHatchDestination; }
/// @notice The Constructor assigns the `escapeHatchDestination` and the /// `escapeHatchCaller` /// @param _escapeHatchDestination The address of a safe location (usu a /// Multisig) to send the ether held in this contract /// @param _escapeHatchCaller The address of a trusted account or contract to /// call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal that `escapeHatchCaller` cannot move /// funds out of `escapeHatchDestination`
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://68cd6154297c049e19a780d0ef661705ad3182cbc26e6886b7998f84aa4cfa7b
{ "func_code_index": [ 656, 857 ] }
10,995
Vault
Vault.sol
0x598ab825d607ace3b00d8714c0a141c7ae2e6822
Solidity
Escapable
contract Escapable is Owned { address public escapeHatchCaller; address public escapeHatchDestination; /// @notice The Constructor assigns the `escapeHatchDestination` and the /// `escapeHatchCaller` /// @param _escapeHatchDestination The address of a safe location (usu a /// Multisig) to send the ether held in this contract /// @param _escapeHatchCaller The address of a trusted account or contract to /// call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal that `escapeHatchCaller` cannot move /// funds out of `escapeHatchDestination` function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) { escapeHatchCaller = _escapeHatchCaller; escapeHatchDestination = _escapeHatchDestination; } /// @dev The addresses preassigned the `escapeHatchCaller` role /// is the only addresses that can call a function with this modifier modifier onlyEscapeHatchCallerOrOwner { if ((msg.sender != escapeHatchCaller)&&(msg.sender != owner)) throw; _; } /// @notice The `escapeHatch()` should only be called as a last resort if a /// security issue is uncovered or something unexpected happened function escapeHatch() onlyEscapeHatchCallerOrOwner { uint total = this.balance; // Send the total balance of this contract to the `escapeHatchDestination` if (!escapeHatchDestination.send(total)) { throw; } EscapeHatchCalled(total); } /// @notice Changes the address assigned to call `escapeHatch()` /// @param _newEscapeHatchCaller The address of a trusted account or contract to /// call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal that `escapeHatchCaller` cannot /// move funds out of `escapeHatchDestination` function changeEscapeCaller(address _newEscapeHatchCaller) onlyEscapeHatchCallerOrOwner { escapeHatchCaller = _newEscapeHatchCaller; } event EscapeHatchCalled(uint amount); }
/// @dev `Escapable` is a base level contract built off of the `Owned` /// contract that creates an escape hatch function to send its ether to /// `escapeHatchDestination` when called by the `escapeHatchCaller` in the case that /// something unexpected happens
NatSpecSingleLine
escapeHatch
function escapeHatch() onlyEscapeHatchCallerOrOwner { uint total = this.balance; // Send the total balance of this contract to the `escapeHatchDestination` if (!escapeHatchDestination.send(total)) { throw; } EscapeHatchCalled(total); }
/// @notice The `escapeHatch()` should only be called as a last resort if a /// security issue is uncovered or something unexpected happened
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://68cd6154297c049e19a780d0ef661705ad3182cbc26e6886b7998f84aa4cfa7b
{ "func_code_index": [ 1313, 1616 ] }
10,996
Vault
Vault.sol
0x598ab825d607ace3b00d8714c0a141c7ae2e6822
Solidity
Escapable
contract Escapable is Owned { address public escapeHatchCaller; address public escapeHatchDestination; /// @notice The Constructor assigns the `escapeHatchDestination` and the /// `escapeHatchCaller` /// @param _escapeHatchDestination The address of a safe location (usu a /// Multisig) to send the ether held in this contract /// @param _escapeHatchCaller The address of a trusted account or contract to /// call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal that `escapeHatchCaller` cannot move /// funds out of `escapeHatchDestination` function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) { escapeHatchCaller = _escapeHatchCaller; escapeHatchDestination = _escapeHatchDestination; } /// @dev The addresses preassigned the `escapeHatchCaller` role /// is the only addresses that can call a function with this modifier modifier onlyEscapeHatchCallerOrOwner { if ((msg.sender != escapeHatchCaller)&&(msg.sender != owner)) throw; _; } /// @notice The `escapeHatch()` should only be called as a last resort if a /// security issue is uncovered or something unexpected happened function escapeHatch() onlyEscapeHatchCallerOrOwner { uint total = this.balance; // Send the total balance of this contract to the `escapeHatchDestination` if (!escapeHatchDestination.send(total)) { throw; } EscapeHatchCalled(total); } /// @notice Changes the address assigned to call `escapeHatch()` /// @param _newEscapeHatchCaller The address of a trusted account or contract to /// call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal that `escapeHatchCaller` cannot /// move funds out of `escapeHatchDestination` function changeEscapeCaller(address _newEscapeHatchCaller) onlyEscapeHatchCallerOrOwner { escapeHatchCaller = _newEscapeHatchCaller; } event EscapeHatchCalled(uint amount); }
/// @dev `Escapable` is a base level contract built off of the `Owned` /// contract that creates an escape hatch function to send its ether to /// `escapeHatchDestination` when called by the `escapeHatchCaller` in the case that /// something unexpected happens
NatSpecSingleLine
changeEscapeCaller
function changeEscapeCaller(address _newEscapeHatchCaller) onlyEscapeHatchCallerOrOwner { escapeHatchCaller = _newEscapeHatchCaller; }
/// @notice Changes the address assigned to call `escapeHatch()` /// @param _newEscapeHatchCaller The address of a trusted account or contract to /// call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal that `escapeHatchCaller` cannot /// move funds out of `escapeHatchDestination`
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://68cd6154297c049e19a780d0ef661705ad3182cbc26e6886b7998f84aa4cfa7b
{ "func_code_index": [ 1984, 2137 ] }
10,997
Vault
Vault.sol
0x598ab825d607ace3b00d8714c0a141c7ae2e6822
Solidity
Vault
contract Vault is Escapable { /// @dev `Payment` is a public structure that describes the details of /// each payment making it easy to track the movement of funds /// transparently struct Payment { string name; // What is the purpose of this payment bytes32 reference; // Reference of the payment. address spender; // Who is sending the funds uint earliestPayTime; // The earliest a payment can be made (Unix Time) bool canceled; // If True then the payment has been canceled bool paid; // If True then the payment has been paid address recipient; // Who is receiving the funds uint amount; // The amount of wei sent in the payment uint securityGuardDelay;// The seconds `securityGuard` can delay payment } Payment[] public authorizedPayments; address public securityGuard; uint public absoluteMinTimeLock; uint public timeLock; uint public maxSecurityGuardDelay; /// @dev The white list of approved addresses allowed to set up && receive /// payments from this vault mapping (address => bool) public allowedSpenders; /// @dev The address assigned the role of `securityGuard` is the only /// addresses that can call a function with this modifier modifier onlySecurityGuard { if (msg.sender != securityGuard) throw; _; } // @dev Events to make the payment movements easy to find on the blockchain event PaymentAuthorized(uint indexed idPayment, address indexed recipient, uint amount); event PaymentExecuted(uint indexed idPayment, address indexed recipient, uint amount); event PaymentCanceled(uint indexed idPayment); event EtherReceived(address indexed from, uint amount); event SpenderAuthorization(address indexed spender, bool authorized); ///////// // Constructor ///////// /// @notice The Constructor creates the Vault on the blockchain /// @param _escapeHatchCaller The address of a trusted account or contract to /// call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal if `escapeHatchCaller` cannot move /// funds out of `escapeHatchDestination` /// @param _escapeHatchDestination The address of a safe location (usu a /// Multisig) to send the ether held in this contract in an emergency /// @param _absoluteMinTimeLock The minimum number of seconds `timelock` can /// be set to, if set to 0 the `owner` can remove the `timeLock` completely /// @param _timeLock Initial number of seconds that payments are delayed /// after they are authorized (a security precaution) /// @param _securityGuard Address that will be able to delay the payments /// beyond the initial timelock requirements; can be set to 0x0 to remove /// the `securityGuard` functionality /// @param _maxSecurityGuardDelay The maximum number of seconds in total /// that `securityGuard` can delay a payment so that the owner can cancel /// the payment if needed function Vault( address _escapeHatchCaller, address _escapeHatchDestination, uint _absoluteMinTimeLock, uint _timeLock, address _securityGuard, uint _maxSecurityGuardDelay) Escapable(_escapeHatchCaller, _escapeHatchDestination) { absoluteMinTimeLock = _absoluteMinTimeLock; timeLock = _timeLock; securityGuard = _securityGuard; maxSecurityGuardDelay = _maxSecurityGuardDelay; } ///////// // Helper functions ///////// /// @notice States the total number of authorized payments in this contract /// @return The number of payments ever authorized even if they were canceled function numberOfAuthorizedPayments() constant returns (uint) { return authorizedPayments.length; } ////// // Receive Ether ////// /// @notice Called anytime ether is sent to the contract && creates an event /// to more easily track the incoming transactions function receiveEther() payable { EtherReceived(msg.sender, msg.value); } /// @notice The fall back function is called whenever ether is sent to this /// contract function () payable { receiveEther(); } //////// // Spender Interface //////// /// @notice only `allowedSpenders[]` Creates a new `Payment` /// @param _name Brief description of the payment that is authorized /// @param _reference External reference of the payment /// @param _recipient Destination of the payment /// @param _amount Amount to be paid in wei /// @param _paymentDelay Number of seconds the payment is to be delayed, if /// this value is below `timeLock` then the `timeLock` determines the delay /// @return The Payment ID number for the new authorized payment function authorizePayment( string _name, bytes32 _reference, address _recipient, uint _amount, uint _paymentDelay ) returns(uint) { // Fail if you arent on the `allowedSpenders` white list if (!allowedSpenders[msg.sender] ) throw; uint idPayment = authorizedPayments.length; // Unique Payment ID authorizedPayments.length++; // The following lines fill out the payment struct Payment p = authorizedPayments[idPayment]; p.spender = msg.sender; // Overflow protection if (_paymentDelay > 10**18) throw; // Determines the earliest the recipient can receive payment (Unix time) p.earliestPayTime = _paymentDelay >= timeLock ? now + _paymentDelay : now + timeLock; p.recipient = _recipient; p.amount = _amount; p.name = _name; p.reference = _reference; PaymentAuthorized(idPayment, p.recipient, p.amount); return idPayment; } /// @notice only `allowedSpenders[]` The recipient of a payment calls this /// function to send themselves the ether after the `earliestPayTime` has /// expired /// @param _idPayment The payment ID to be executed function collectAuthorizedPayment(uint _idPayment) { // Check that the `_idPayment` has been added to the payments struct if (_idPayment >= authorizedPayments.length) throw; Payment p = authorizedPayments[_idPayment]; // Checking for reasons not to execute the payment if (msg.sender != p.recipient) throw; if (!allowedSpenders[p.spender]) throw; if (now < p.earliestPayTime) throw; if (p.canceled) throw; if (p.paid) throw; if (this.balance < p.amount) throw; p.paid = true; // Set the payment to being paid if (!p.recipient.send(p.amount)) { // Make the payment throw; } PaymentExecuted(_idPayment, p.recipient, p.amount); } ///////// // SecurityGuard Interface ///////// /// @notice `onlySecurityGuard` Delays a payment for a set number of seconds /// @param _idPayment ID of the payment to be delayed /// @param _delay The number of seconds to delay the payment function delayPayment(uint _idPayment, uint _delay) onlySecurityGuard { if (_idPayment >= authorizedPayments.length) throw; // Overflow test if (_delay > 10**18) throw; Payment p = authorizedPayments[_idPayment]; if ((p.securityGuardDelay + _delay > maxSecurityGuardDelay) || (p.paid) || (p.canceled)) throw; p.securityGuardDelay += _delay; p.earliestPayTime += _delay; } //////// // Owner Interface /////// /// @notice `onlyOwner` Cancel a payment all together /// @param _idPayment ID of the payment to be canceled. function cancelPayment(uint _idPayment) onlyOwner { if (_idPayment >= authorizedPayments.length) throw; Payment p = authorizedPayments[_idPayment]; if (p.canceled) throw; if (p.paid) throw; p.canceled = true; PaymentCanceled(_idPayment); } /// @notice `onlyOwner` Adds a spender to the `allowedSpenders[]` white list /// @param _spender The address of the contract being authorized/unauthorized /// @param _authorize `true` if authorizing and `false` if unauthorizing function authorizeSpender(address _spender, bool _authorize) onlyOwner { allowedSpenders[_spender] = _authorize; SpenderAuthorization(_spender, _authorize); } /// @notice `onlyOwner` Sets the address of `securityGuard` /// @param _newSecurityGuard Address of the new security guard function setSecurityGuard(address _newSecurityGuard) onlyOwner { securityGuard = _newSecurityGuard; } /// @notice `onlyOwner` Changes `timeLock`; the new `timeLock` cannot be /// lower than `absoluteMinTimeLock` /// @param _newTimeLock Sets the new minimum default `timeLock` in seconds; /// pending payments maintain their `earliestPayTime` function setTimelock(uint _newTimeLock) onlyOwner { if (_newTimeLock < absoluteMinTimeLock) throw; timeLock = _newTimeLock; } /// @notice `onlyOwner` Changes the maximum number of seconds /// `securityGuard` can delay a payment /// @param _maxSecurityGuardDelay The new maximum delay in seconds that /// `securityGuard` can delay the payment's execution in total function setMaxSecurityGuardDelay(uint _maxSecurityGuardDelay) onlyOwner { maxSecurityGuardDelay = _maxSecurityGuardDelay; } }
/// @dev `Vault` is a higher level contract built off of the `Escapable` /// contract that holds funds for Campaigns and automates payments.
NatSpecSingleLine
Vault
function Vault( address _escapeHatchCaller, address _escapeHatchDestination, uint _absoluteMinTimeLock, uint _timeLock, address _securityGuard, uint _maxSecurityGuardDelay) Escapable(_escapeHatchCaller, _escapeHatchDestination) { absoluteMinTimeLock = _absoluteMinTimeLock; timeLock = _timeLock; securityGuard = _securityGuard; maxSecurityGuardDelay = _maxSecurityGuardDelay; }
///////// /// @notice The Constructor creates the Vault on the blockchain /// @param _escapeHatchCaller The address of a trusted account or contract to /// call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal if `escapeHatchCaller` cannot move /// funds out of `escapeHatchDestination` /// @param _escapeHatchDestination The address of a safe location (usu a /// Multisig) to send the ether held in this contract in an emergency /// @param _absoluteMinTimeLock The minimum number of seconds `timelock` can /// be set to, if set to 0 the `owner` can remove the `timeLock` completely /// @param _timeLock Initial number of seconds that payments are delayed /// after they are authorized (a security precaution) /// @param _securityGuard Address that will be able to delay the payments /// beyond the initial timelock requirements; can be set to 0x0 to remove /// the `securityGuard` functionality /// @param _maxSecurityGuardDelay The maximum number of seconds in total /// that `securityGuard` can delay a payment so that the owner can cancel /// the payment if needed
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://68cd6154297c049e19a780d0ef661705ad3182cbc26e6886b7998f84aa4cfa7b
{ "func_code_index": [ 3159, 3641 ] }
10,998
Vault
Vault.sol
0x598ab825d607ace3b00d8714c0a141c7ae2e6822
Solidity
Vault
contract Vault is Escapable { /// @dev `Payment` is a public structure that describes the details of /// each payment making it easy to track the movement of funds /// transparently struct Payment { string name; // What is the purpose of this payment bytes32 reference; // Reference of the payment. address spender; // Who is sending the funds uint earliestPayTime; // The earliest a payment can be made (Unix Time) bool canceled; // If True then the payment has been canceled bool paid; // If True then the payment has been paid address recipient; // Who is receiving the funds uint amount; // The amount of wei sent in the payment uint securityGuardDelay;// The seconds `securityGuard` can delay payment } Payment[] public authorizedPayments; address public securityGuard; uint public absoluteMinTimeLock; uint public timeLock; uint public maxSecurityGuardDelay; /// @dev The white list of approved addresses allowed to set up && receive /// payments from this vault mapping (address => bool) public allowedSpenders; /// @dev The address assigned the role of `securityGuard` is the only /// addresses that can call a function with this modifier modifier onlySecurityGuard { if (msg.sender != securityGuard) throw; _; } // @dev Events to make the payment movements easy to find on the blockchain event PaymentAuthorized(uint indexed idPayment, address indexed recipient, uint amount); event PaymentExecuted(uint indexed idPayment, address indexed recipient, uint amount); event PaymentCanceled(uint indexed idPayment); event EtherReceived(address indexed from, uint amount); event SpenderAuthorization(address indexed spender, bool authorized); ///////// // Constructor ///////// /// @notice The Constructor creates the Vault on the blockchain /// @param _escapeHatchCaller The address of a trusted account or contract to /// call `escapeHatch()` to send the ether in this contract to the /// `escapeHatchDestination` it would be ideal if `escapeHatchCaller` cannot move /// funds out of `escapeHatchDestination` /// @param _escapeHatchDestination The address of a safe location (usu a /// Multisig) to send the ether held in this contract in an emergency /// @param _absoluteMinTimeLock The minimum number of seconds `timelock` can /// be set to, if set to 0 the `owner` can remove the `timeLock` completely /// @param _timeLock Initial number of seconds that payments are delayed /// after they are authorized (a security precaution) /// @param _securityGuard Address that will be able to delay the payments /// beyond the initial timelock requirements; can be set to 0x0 to remove /// the `securityGuard` functionality /// @param _maxSecurityGuardDelay The maximum number of seconds in total /// that `securityGuard` can delay a payment so that the owner can cancel /// the payment if needed function Vault( address _escapeHatchCaller, address _escapeHatchDestination, uint _absoluteMinTimeLock, uint _timeLock, address _securityGuard, uint _maxSecurityGuardDelay) Escapable(_escapeHatchCaller, _escapeHatchDestination) { absoluteMinTimeLock = _absoluteMinTimeLock; timeLock = _timeLock; securityGuard = _securityGuard; maxSecurityGuardDelay = _maxSecurityGuardDelay; } ///////// // Helper functions ///////// /// @notice States the total number of authorized payments in this contract /// @return The number of payments ever authorized even if they were canceled function numberOfAuthorizedPayments() constant returns (uint) { return authorizedPayments.length; } ////// // Receive Ether ////// /// @notice Called anytime ether is sent to the contract && creates an event /// to more easily track the incoming transactions function receiveEther() payable { EtherReceived(msg.sender, msg.value); } /// @notice The fall back function is called whenever ether is sent to this /// contract function () payable { receiveEther(); } //////// // Spender Interface //////// /// @notice only `allowedSpenders[]` Creates a new `Payment` /// @param _name Brief description of the payment that is authorized /// @param _reference External reference of the payment /// @param _recipient Destination of the payment /// @param _amount Amount to be paid in wei /// @param _paymentDelay Number of seconds the payment is to be delayed, if /// this value is below `timeLock` then the `timeLock` determines the delay /// @return The Payment ID number for the new authorized payment function authorizePayment( string _name, bytes32 _reference, address _recipient, uint _amount, uint _paymentDelay ) returns(uint) { // Fail if you arent on the `allowedSpenders` white list if (!allowedSpenders[msg.sender] ) throw; uint idPayment = authorizedPayments.length; // Unique Payment ID authorizedPayments.length++; // The following lines fill out the payment struct Payment p = authorizedPayments[idPayment]; p.spender = msg.sender; // Overflow protection if (_paymentDelay > 10**18) throw; // Determines the earliest the recipient can receive payment (Unix time) p.earliestPayTime = _paymentDelay >= timeLock ? now + _paymentDelay : now + timeLock; p.recipient = _recipient; p.amount = _amount; p.name = _name; p.reference = _reference; PaymentAuthorized(idPayment, p.recipient, p.amount); return idPayment; } /// @notice only `allowedSpenders[]` The recipient of a payment calls this /// function to send themselves the ether after the `earliestPayTime` has /// expired /// @param _idPayment The payment ID to be executed function collectAuthorizedPayment(uint _idPayment) { // Check that the `_idPayment` has been added to the payments struct if (_idPayment >= authorizedPayments.length) throw; Payment p = authorizedPayments[_idPayment]; // Checking for reasons not to execute the payment if (msg.sender != p.recipient) throw; if (!allowedSpenders[p.spender]) throw; if (now < p.earliestPayTime) throw; if (p.canceled) throw; if (p.paid) throw; if (this.balance < p.amount) throw; p.paid = true; // Set the payment to being paid if (!p.recipient.send(p.amount)) { // Make the payment throw; } PaymentExecuted(_idPayment, p.recipient, p.amount); } ///////// // SecurityGuard Interface ///////// /// @notice `onlySecurityGuard` Delays a payment for a set number of seconds /// @param _idPayment ID of the payment to be delayed /// @param _delay The number of seconds to delay the payment function delayPayment(uint _idPayment, uint _delay) onlySecurityGuard { if (_idPayment >= authorizedPayments.length) throw; // Overflow test if (_delay > 10**18) throw; Payment p = authorizedPayments[_idPayment]; if ((p.securityGuardDelay + _delay > maxSecurityGuardDelay) || (p.paid) || (p.canceled)) throw; p.securityGuardDelay += _delay; p.earliestPayTime += _delay; } //////// // Owner Interface /////// /// @notice `onlyOwner` Cancel a payment all together /// @param _idPayment ID of the payment to be canceled. function cancelPayment(uint _idPayment) onlyOwner { if (_idPayment >= authorizedPayments.length) throw; Payment p = authorizedPayments[_idPayment]; if (p.canceled) throw; if (p.paid) throw; p.canceled = true; PaymentCanceled(_idPayment); } /// @notice `onlyOwner` Adds a spender to the `allowedSpenders[]` white list /// @param _spender The address of the contract being authorized/unauthorized /// @param _authorize `true` if authorizing and `false` if unauthorizing function authorizeSpender(address _spender, bool _authorize) onlyOwner { allowedSpenders[_spender] = _authorize; SpenderAuthorization(_spender, _authorize); } /// @notice `onlyOwner` Sets the address of `securityGuard` /// @param _newSecurityGuard Address of the new security guard function setSecurityGuard(address _newSecurityGuard) onlyOwner { securityGuard = _newSecurityGuard; } /// @notice `onlyOwner` Changes `timeLock`; the new `timeLock` cannot be /// lower than `absoluteMinTimeLock` /// @param _newTimeLock Sets the new minimum default `timeLock` in seconds; /// pending payments maintain their `earliestPayTime` function setTimelock(uint _newTimeLock) onlyOwner { if (_newTimeLock < absoluteMinTimeLock) throw; timeLock = _newTimeLock; } /// @notice `onlyOwner` Changes the maximum number of seconds /// `securityGuard` can delay a payment /// @param _maxSecurityGuardDelay The new maximum delay in seconds that /// `securityGuard` can delay the payment's execution in total function setMaxSecurityGuardDelay(uint _maxSecurityGuardDelay) onlyOwner { maxSecurityGuardDelay = _maxSecurityGuardDelay; } }
/// @dev `Vault` is a higher level contract built off of the `Escapable` /// contract that holds funds for Campaigns and automates payments.
NatSpecSingleLine
numberOfAuthorizedPayments
function numberOfAuthorizedPayments() constant returns (uint) { return authorizedPayments.length; }
///////// /// @notice States the total number of authorized payments in this contract /// @return The number of payments ever authorized even if they were canceled
NatSpecSingleLine
v0.4.18+commit.9cf6e910
bzzr://68cd6154297c049e19a780d0ef661705ad3182cbc26e6886b7998f84aa4cfa7b
{ "func_code_index": [ 3853, 3971 ] }
10,999