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
EOSBetSlots
EOSBetSlots.sol
0x4a3e0c60f7fa67e8b65c401ddbbf7c17fea5fe40
Solidity
EOSBetSlots
contract EOSBetSlots is usingOraclize, EOSBetGameInterface { using SafeMath for *; // events event BuyCredits(bytes32 indexed oraclizeQueryId); event LedgerProofFailed(bytes32 indexed oraclizeQueryId); event Refund(bytes32 indexed oraclizeQueryId, uint256 amount); event SlotsLargeBet(bytes32 indexed oraclizeQueryId, uint256 data1, uint256 data2, uint256 data3, uint256 data4, uint256 data5, uint256 data6, uint256 data7, uint256 data8); event SlotsSmallBet(uint256 data1, uint256 data2, uint256 data3, uint256 data4, uint256 data5, uint256 data6, uint256 data7, uint256 data8); // slots game structure struct SlotsGameData { address player; bool paidOut; uint256 start; uint256 etherReceived; uint8 credits; } mapping (bytes32 => SlotsGameData) public slotsData; // ether in this contract can be in one of two locations: uint256 public LIABILITIES; uint256 public DEVELOPERSFUND; // counters for frontend statistics uint256 public AMOUNTWAGERED; uint256 public DIALSSPUN; // togglable values uint256 public ORACLIZEQUERYMAXTIME; uint256 public MINBET_perSPIN; uint256 public MINBET_perTX; uint256 public ORACLIZEGASPRICE; uint256 public INITIALGASFORORACLIZE; uint16 public MAXWIN_inTHOUSANDTHPERCENTS; // togglable functionality of contract bool public GAMEPAUSED; bool public REFUNDSACTIVE; // owner of contract address public OWNER; // bankroller address address public BANKROLLER; // constructor function EOSBetSlots() public { // ledger proof is ALWAYS verified on-chain oraclize_setProof(proofType_Ledger); // gas prices for oraclize call back, can be changed oraclize_setCustomGasPrice(8000000000); ORACLIZEGASPRICE = 8000000000; INITIALGASFORORACLIZE = 225000; AMOUNTWAGERED = 0; DIALSSPUN = 0; GAMEPAUSED = false; REFUNDSACTIVE = true; ORACLIZEQUERYMAXTIME = 6 hours; MINBET_perSPIN = 2 finney; // currently, this is ~40-50c a spin, which is pretty average slots. This is changeable by OWNER MINBET_perTX = 10 finney; MAXWIN_inTHOUSANDTHPERCENTS = 333; // 333/1000 so a jackpot can take 33% of bankroll (extremely rare) OWNER = msg.sender; } //////////////////////////////////// // INTERFACE CONTACT FUNCTIONS //////////////////////////////////// function payDevelopersFund(address developer) public { require(msg.sender == BANKROLLER); uint256 devFund = DEVELOPERSFUND; DEVELOPERSFUND = 0; developer.transfer(devFund); } // just a function to receive eth, only allow the bankroll to use this function receivePaymentForOraclize() payable public { require(msg.sender == BANKROLLER); } //////////////////////////////////// // VIEW FUNCTIONS //////////////////////////////////// function getMaxWin() public view returns(uint256){ return (SafeMath.mul(EOSBetBankrollInterface(BANKROLLER).getBankroll(), MAXWIN_inTHOUSANDTHPERCENTS) / 1000); } //////////////////////////////////// // OWNER ONLY FUNCTIONS //////////////////////////////////// // WARNING!!!!! Can only set this function once! function setBankrollerContractOnce(address bankrollAddress) public { // require that BANKROLLER address == 0x0 (address not set yet), and coming from owner. require(msg.sender == OWNER && BANKROLLER == address(0)); // check here to make sure that the bankroll contract is legitimate // just make sure that calling the bankroll contract getBankroll() returns non-zero require(EOSBetBankrollInterface(bankrollAddress).getBankroll() != 0); BANKROLLER = bankrollAddress; } function transferOwnership(address newOwner) public { require(msg.sender == OWNER); OWNER = newOwner; } function setOraclizeQueryMaxTime(uint256 newTime) public { require(msg.sender == OWNER); ORACLIZEQUERYMAXTIME = newTime; } // store the gas price as a storage variable for easy reference, // and thne change the gas price using the proper oraclize function function setOraclizeQueryGasPrice(uint256 gasPrice) public { require(msg.sender == OWNER); ORACLIZEGASPRICE = gasPrice; oraclize_setCustomGasPrice(gasPrice); } // should be ~160,000 to save eth function setInitialGasForOraclize(uint256 gasAmt) public { require(msg.sender == OWNER); INITIALGASFORORACLIZE = gasAmt; } function setGamePaused(bool paused) public { require(msg.sender == OWNER); GAMEPAUSED = paused; } function setRefundsActive(bool active) public { require(msg.sender == OWNER); REFUNDSACTIVE = active; } function setMinBetPerSpin(uint256 minBet) public { require(msg.sender == OWNER && minBet > 1000); MINBET_perSPIN = minBet; } function setMinBetPerTx(uint256 minBet) public { require(msg.sender == OWNER && minBet > 1000); MINBET_perTX = minBet; } function setMaxwin(uint16 newMaxWinInThousandthPercents) public { require(msg.sender == OWNER && newMaxWinInThousandthPercents <= 333); // cannot set max win greater than 1/3 of the bankroll (a jackpot is very rare) MAXWIN_inTHOUSANDTHPERCENTS = newMaxWinInThousandthPercents; } // rescue tokens inadvertently sent to the contract address function ERC20Rescue(address tokenAddress, uint256 amtTokens) public { require (msg.sender == OWNER); ERC20(tokenAddress).transfer(msg.sender, amtTokens); } function refund(bytes32 oraclizeQueryId) public { // save into memory for cheap access SlotsGameData memory data = slotsData[oraclizeQueryId]; //require that the query time is too slow, bet has not been paid out, and either contract owner or player is calling this function. require(SafeMath.sub(block.timestamp, data.start) >= ORACLIZEQUERYMAXTIME && (msg.sender == OWNER || msg.sender == data.player) && (!data.paidOut) && data.etherReceived <= LIABILITIES && data.etherReceived > 0 && REFUNDSACTIVE); // set contract data slotsData[oraclizeQueryId].paidOut = true; // subtract etherReceived from these two values because the bet is being refunded LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived); // then transfer the original bet to the player. data.player.transfer(data.etherReceived); // finally, log an event saying that the refund has processed. emit Refund(oraclizeQueryId, data.etherReceived); } function play(uint8 credits) public payable { // save for future use / gas efficiency uint256 betPerCredit = msg.value / credits; // require that the game is unpaused, and that the credits being purchased are greater than 0 and less than the allowed amount, default: 100 spins // verify that the bet is less than or equal to the bet limit, so we don't go bankrupt, and that the etherreceived is greater than the minbet. require(!GAMEPAUSED && msg.value >= MINBET_perTX && betPerCredit >= MINBET_perSPIN && credits > 0 && credits <= 224 && SafeMath.mul(betPerCredit, 5000) <= getMaxWin()); // 5000 is the jackpot payout (max win on a roll) // equation for gas to oraclize is: // gas = (some fixed gas amt) + 3270 * credits uint256 gasToSend = INITIALGASFORORACLIZE + (uint256(3270) * credits); EOSBetBankrollInterface(BANKROLLER).payOraclize(oraclize_getPrice('random', gasToSend)); // oraclize_newRandomDSQuery(delay in seconds, bytes of random data, gas for callback function) bytes32 oraclizeQueryId = oraclize_newRandomDSQuery(0, 30, gasToSend); // add the new slots data to a mapping so that the oraclize __callback can use it later slotsData[oraclizeQueryId] = SlotsGameData({ player : msg.sender, paidOut : false, start : block.timestamp, etherReceived : msg.value, credits : credits }); // add the sent value into liabilities. this should NOT go into the bankroll yet // and must be quarantined here to prevent timing attacks LIABILITIES = SafeMath.add(LIABILITIES, msg.value); emit BuyCredits(oraclizeQueryId); } function __callback(bytes32 _queryId, string _result, bytes _proof) public { // get the game data and put into memory SlotsGameData memory data = slotsData[_queryId]; require(msg.sender == oraclize_cbAddress() && !data.paidOut && data.player != address(0) && LIABILITIES >= data.etherReceived); // if the proof has failed, immediately refund the player the original bet. if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0){ if (REFUNDSACTIVE){ // set contract data slotsData[_queryId].paidOut = true; // subtract from liabilities and amount wagered, because this bet is being refunded. LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived); // transfer the original bet back data.player.transfer(data.etherReceived); // log the refund emit Refund(_queryId, data.etherReceived); } // log the ledger proof fail emit LedgerProofFailed(_queryId); } else { // again, this block is almost identical to the previous block in the play(...) function // instead of duplicating documentation, we will just point out the changes from the other block uint256 dialsSpun; uint8 dial1; uint8 dial2; uint8 dial3; uint256[] memory logsData = new uint256[](8); uint256 payout; // must use data.credits instead of credits. for (uint8 i = 0; i < data.credits; i++){ // all dials now use _result, instead of blockhash, this is the main change, and allows Slots to // accomodate bets of any size, free of possible miner interference dialsSpun += 1; dial1 = uint8(uint(keccak256(_result, dialsSpun)) % 64); dialsSpun += 1; dial2 = uint8(uint(keccak256(_result, dialsSpun)) % 64); dialsSpun += 1; dial3 = uint8(uint(keccak256(_result, dialsSpun)) % 64); // dial 1 dial1 = getDial1Type(dial1); // dial 2 dial2 = getDial2Type(dial2); // dial 3 dial3 = getDial3Type(dial3); // determine the payout payout += determinePayout(dial1, dial2, dial3); // assembling log data if (i <= 27){ // in logsData0 logsData[0] += uint256(dial1) * uint256(2) ** (3 * ((3 * (27 - i)) + 2)); logsData[0] += uint256(dial2) * uint256(2) ** (3 * ((3 * (27 - i)) + 1)); logsData[0] += uint256(dial3) * uint256(2) ** (3 * ((3 * (27 - i)))); } else if (i <= 55){ // in logsData1 logsData[1] += uint256(dial1) * uint256(2) ** (3 * ((3 * (55 - i)) + 2)); logsData[1] += uint256(dial2) * uint256(2) ** (3 * ((3 * (55 - i)) + 1)); logsData[1] += uint256(dial3) * uint256(2) ** (3 * ((3 * (55 - i)))); } else if (i <= 83) { // in logsData2 logsData[2] += uint256(dial1) * uint256(2) ** (3 * ((3 * (83 - i)) + 2)); logsData[2] += uint256(dial2) * uint256(2) ** (3 * ((3 * (83 - i)) + 1)); logsData[2] += uint256(dial3) * uint256(2) ** (3 * ((3 * (83 - i)))); } else if (i <= 111) { // in logsData3 logsData[3] += uint256(dial1) * uint256(2) ** (3 * ((3 * (111 - i)) + 2)); logsData[3] += uint256(dial2) * uint256(2) ** (3 * ((3 * (111 - i)) + 1)); logsData[3] += uint256(dial3) * uint256(2) ** (3 * ((3 * (111 - i)))); } else if (i <= 139){ // in logsData4 logsData[4] += uint256(dial1) * uint256(2) ** (3 * ((3 * (139 - i)) + 2)); logsData[4] += uint256(dial2) * uint256(2) ** (3 * ((3 * (139 - i)) + 1)); logsData[4] += uint256(dial3) * uint256(2) ** (3 * ((3 * (139 - i)))); } else if (i <= 167){ // in logsData5 logsData[5] += uint256(dial1) * uint256(2) ** (3 * ((3 * (167 - i)) + 2)); logsData[5] += uint256(dial2) * uint256(2) ** (3 * ((3 * (167 - i)) + 1)); logsData[5] += uint256(dial3) * uint256(2) ** (3 * ((3 * (167 - i)))); } else if (i <= 195){ // in logsData6 logsData[6] += uint256(dial1) * uint256(2) ** (3 * ((3 * (195 - i)) + 2)); logsData[6] += uint256(dial2) * uint256(2) ** (3 * ((3 * (195 - i)) + 1)); logsData[6] += uint256(dial3) * uint256(2) ** (3 * ((3 * (195 - i)))); } else if (i <= 223){ // in logsData7 logsData[7] += uint256(dial1) * uint256(2) ** (3 * ((3 * (223 - i)) + 2)); logsData[7] += uint256(dial2) * uint256(2) ** (3 * ((3 * (223 - i)) + 1)); logsData[7] += uint256(dial3) * uint256(2) ** (3 * ((3 * (223 - i)))); } } // track that these spins were made DIALSSPUN += dialsSpun; // and add the amount wagered AMOUNTWAGERED = SafeMath.add(AMOUNTWAGERED, data.etherReceived); // IMPORTANT: we must change the "paidOut" to TRUE here to prevent reentrancy/other nasty effects. // this was not needed with the previous loop/code block, and is used because variables must be written into storage slotsData[_queryId].paidOut = true; // decrease LIABILITIES when the spins are made LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived); // get the developers cut, and send the rest of the ether received to the bankroller contract uint256 developersCut = data.etherReceived / 100; DEVELOPERSFUND = SafeMath.add(DEVELOPERSFUND, developersCut); EOSBetBankrollInterface(BANKROLLER).receiveEtherFromGameAddress.value(SafeMath.sub(data.etherReceived, developersCut))(); // get the ether to be paid out, and force the bankroller contract to pay out the player uint256 etherPaidout = SafeMath.mul((data.etherReceived / data.credits), payout); EOSBetBankrollInterface(BANKROLLER).payEtherToWinner(etherPaidout, data.player); // log en event with indexed query id emit SlotsLargeBet(_queryId, logsData[0], logsData[1], logsData[2], logsData[3], logsData[4], logsData[5], logsData[6], logsData[7]); } } // HELPER FUNCTIONS TO: // calculate the result of the dials based on the hardcoded slot data: // STOPS REEL#1 REEL#2 REEL#3 /////////////////////////////////////////// // gold ether 0 // 1 // 3 // 1 // // silver ether 1 // 7 // 1 // 6 // // bronze ether 2 // 1 // 7 // 6 // // gold planet 3 // 5 // 7 // 6 // // silverplanet 4 // 9 // 6 // 7 // // bronzeplanet 5 // 9 // 8 // 6 // // ---blank--- 6 // 32 // 32 // 32 // /////////////////////////////////////////// // note that dial1 / 2 / 3 will go from mod 64 to mod 7 in this manner function getDial1Type(uint8 dial1Location) internal pure returns(uint8) { if (dial1Location == 0) { return 0; } else if (dial1Location >= 1 && dial1Location <= 7) { return 1; } else if (dial1Location == 8) { return 2; } else if (dial1Location >= 9 && dial1Location <= 13) { return 3; } else if (dial1Location >= 14 && dial1Location <= 22) { return 4; } else if (dial1Location >= 23 && dial1Location <= 31) { return 5; } else { return 6; } } function getDial2Type(uint8 dial2Location) internal pure returns(uint8) { if (dial2Location >= 0 && dial2Location <= 2) { return 0; } else if (dial2Location == 3) { return 1; } else if (dial2Location >= 4 && dial2Location <= 10) { return 2; } else if (dial2Location >= 11 && dial2Location <= 17) { return 3; } else if (dial2Location >= 18 && dial2Location <= 23) { return 4; } else if (dial2Location >= 24 && dial2Location <= 31) { return 5; } else { return 6; } } function getDial3Type(uint8 dial3Location) internal pure returns(uint8) { if (dial3Location == 0) { return 0; } else if (dial3Location >= 1 && dial3Location <= 6) { return 1; } else if (dial3Location >= 7 && dial3Location <= 12) { return 2; } else if (dial3Location >= 13 && dial3Location <= 18) { return 3; } else if (dial3Location >= 19 && dial3Location <= 25) { return 4; } else if (dial3Location >= 26 && dial3Location <= 31) { return 5; } else { return 6; } } // HELPER FUNCTION TO: // determine the payout given dial locations based on this table // hardcoded payouts data: // LANDS ON // PAYS // //////////////////////////////////////////////// // Bronze E -> Silver E -> Gold E // 5000 // // 3x Gold Ether // 1777 // // 3x Silver Ether // 250 // // 3x Bronze Ether // 250 // // Bronze P -> Silver P -> Gold P // 90 // // 3x any Ether // 70 // // 3x Gold Planet // 50 // // 3x Silver Planet // 25 // // Any Gold P & Silver P & Bronze P // 15 // // 3x Bronze Planet // 10 // // Any 3 planet type // 3 // // Any 3 gold // 3 // // Any 3 silver // 2 // // Any 3 bronze // 2 // // Blank, blank, blank // 1 // // else // 0 // //////////////////////////////////////////////// function determinePayout(uint8 dial1, uint8 dial2, uint8 dial3) internal pure returns(uint256) { if (dial1 == 6 || dial2 == 6 || dial3 == 6){ // all blank if (dial1 == 6 && dial2 == 6 && dial3 == 6) return 1; } else if (dial1 == 5){ // bronze planet -> silver planet -> gold planet if (dial2 == 4 && dial3 == 3) return 90; // one gold planet, one silver planet, one bronze planet, any order! // note: other order covered above, return 90 else if (dial2 == 3 && dial3 == 4) return 15; // all bronze planet else if (dial2 == 5 && dial3 == 5) return 10; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three bronze else if ((dial2 == 2 || dial2 == 5) && (dial3 == 2 || dial3 == 5)) return 2; } else if (dial1 == 4){ // all silver planet if (dial2 == 4 && dial3 == 4) return 25; // one gold planet, one silver planet, one bronze planet, any order! else if ((dial2 == 3 && dial3 == 5) || (dial2 == 5 && dial3 == 3)) return 15; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three silver else if ((dial2 == 1 || dial2 == 4) && (dial3 == 1 || dial3 == 4)) return 2; } else if (dial1 == 3){ // all gold planet if (dial2 == 3 && dial3 == 3) return 50; // one gold planet, one silver planet, one bronze planet, any order! else if ((dial2 == 4 && dial3 == 5) || (dial2 == 5 && dial3 == 4)) return 15; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three gold else if ((dial2 == 0 || dial2 == 3) && (dial3 == 0 || dial3 == 3)) return 3; } else if (dial1 == 2){ if (dial2 == 1 && dial3 == 0) return 5000; // jackpot!!!! // all bronze ether else if (dial2 == 2 && dial3 == 2) return 250; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three bronze else if ((dial2 == 2 || dial2 == 5) && (dial3 == 2 || dial3 == 5)) return 2; } else if (dial1 == 1){ // all silver ether if (dial2 == 1 && dial3 == 1) return 250; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three silver else if ((dial2 == 1 || dial2 == 4) && (dial3 == 1 || dial3 == 4)) return 3; } else if (dial1 == 0){ // all gold ether if (dial2 == 0 && dial3 == 0) return 1777; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three gold else if ((dial2 == 0 || dial2 == 3) && (dial3 == 0 || dial3 == 3)) return 3; } return 0; } }
setInitialGasForOraclize
function setInitialGasForOraclize(uint256 gasAmt) public { require(msg.sender == OWNER); INITIALGASFORORACLIZE = gasAmt; }
// should be ~160,000 to save eth
LineComment
v0.4.21+commit.dfe3193c
bzzr://2d48f2cf6e8bfcc89fb1b8028c0e9f3ac99194db8d859ddd6bcf058cdfd9d462
{ "func_code_index": [ 4246, 4380 ] }
60,061
EOSBetSlots
EOSBetSlots.sol
0x4a3e0c60f7fa67e8b65c401ddbbf7c17fea5fe40
Solidity
EOSBetSlots
contract EOSBetSlots is usingOraclize, EOSBetGameInterface { using SafeMath for *; // events event BuyCredits(bytes32 indexed oraclizeQueryId); event LedgerProofFailed(bytes32 indexed oraclizeQueryId); event Refund(bytes32 indexed oraclizeQueryId, uint256 amount); event SlotsLargeBet(bytes32 indexed oraclizeQueryId, uint256 data1, uint256 data2, uint256 data3, uint256 data4, uint256 data5, uint256 data6, uint256 data7, uint256 data8); event SlotsSmallBet(uint256 data1, uint256 data2, uint256 data3, uint256 data4, uint256 data5, uint256 data6, uint256 data7, uint256 data8); // slots game structure struct SlotsGameData { address player; bool paidOut; uint256 start; uint256 etherReceived; uint8 credits; } mapping (bytes32 => SlotsGameData) public slotsData; // ether in this contract can be in one of two locations: uint256 public LIABILITIES; uint256 public DEVELOPERSFUND; // counters for frontend statistics uint256 public AMOUNTWAGERED; uint256 public DIALSSPUN; // togglable values uint256 public ORACLIZEQUERYMAXTIME; uint256 public MINBET_perSPIN; uint256 public MINBET_perTX; uint256 public ORACLIZEGASPRICE; uint256 public INITIALGASFORORACLIZE; uint16 public MAXWIN_inTHOUSANDTHPERCENTS; // togglable functionality of contract bool public GAMEPAUSED; bool public REFUNDSACTIVE; // owner of contract address public OWNER; // bankroller address address public BANKROLLER; // constructor function EOSBetSlots() public { // ledger proof is ALWAYS verified on-chain oraclize_setProof(proofType_Ledger); // gas prices for oraclize call back, can be changed oraclize_setCustomGasPrice(8000000000); ORACLIZEGASPRICE = 8000000000; INITIALGASFORORACLIZE = 225000; AMOUNTWAGERED = 0; DIALSSPUN = 0; GAMEPAUSED = false; REFUNDSACTIVE = true; ORACLIZEQUERYMAXTIME = 6 hours; MINBET_perSPIN = 2 finney; // currently, this is ~40-50c a spin, which is pretty average slots. This is changeable by OWNER MINBET_perTX = 10 finney; MAXWIN_inTHOUSANDTHPERCENTS = 333; // 333/1000 so a jackpot can take 33% of bankroll (extremely rare) OWNER = msg.sender; } //////////////////////////////////// // INTERFACE CONTACT FUNCTIONS //////////////////////////////////// function payDevelopersFund(address developer) public { require(msg.sender == BANKROLLER); uint256 devFund = DEVELOPERSFUND; DEVELOPERSFUND = 0; developer.transfer(devFund); } // just a function to receive eth, only allow the bankroll to use this function receivePaymentForOraclize() payable public { require(msg.sender == BANKROLLER); } //////////////////////////////////// // VIEW FUNCTIONS //////////////////////////////////// function getMaxWin() public view returns(uint256){ return (SafeMath.mul(EOSBetBankrollInterface(BANKROLLER).getBankroll(), MAXWIN_inTHOUSANDTHPERCENTS) / 1000); } //////////////////////////////////// // OWNER ONLY FUNCTIONS //////////////////////////////////// // WARNING!!!!! Can only set this function once! function setBankrollerContractOnce(address bankrollAddress) public { // require that BANKROLLER address == 0x0 (address not set yet), and coming from owner. require(msg.sender == OWNER && BANKROLLER == address(0)); // check here to make sure that the bankroll contract is legitimate // just make sure that calling the bankroll contract getBankroll() returns non-zero require(EOSBetBankrollInterface(bankrollAddress).getBankroll() != 0); BANKROLLER = bankrollAddress; } function transferOwnership(address newOwner) public { require(msg.sender == OWNER); OWNER = newOwner; } function setOraclizeQueryMaxTime(uint256 newTime) public { require(msg.sender == OWNER); ORACLIZEQUERYMAXTIME = newTime; } // store the gas price as a storage variable for easy reference, // and thne change the gas price using the proper oraclize function function setOraclizeQueryGasPrice(uint256 gasPrice) public { require(msg.sender == OWNER); ORACLIZEGASPRICE = gasPrice; oraclize_setCustomGasPrice(gasPrice); } // should be ~160,000 to save eth function setInitialGasForOraclize(uint256 gasAmt) public { require(msg.sender == OWNER); INITIALGASFORORACLIZE = gasAmt; } function setGamePaused(bool paused) public { require(msg.sender == OWNER); GAMEPAUSED = paused; } function setRefundsActive(bool active) public { require(msg.sender == OWNER); REFUNDSACTIVE = active; } function setMinBetPerSpin(uint256 minBet) public { require(msg.sender == OWNER && minBet > 1000); MINBET_perSPIN = minBet; } function setMinBetPerTx(uint256 minBet) public { require(msg.sender == OWNER && minBet > 1000); MINBET_perTX = minBet; } function setMaxwin(uint16 newMaxWinInThousandthPercents) public { require(msg.sender == OWNER && newMaxWinInThousandthPercents <= 333); // cannot set max win greater than 1/3 of the bankroll (a jackpot is very rare) MAXWIN_inTHOUSANDTHPERCENTS = newMaxWinInThousandthPercents; } // rescue tokens inadvertently sent to the contract address function ERC20Rescue(address tokenAddress, uint256 amtTokens) public { require (msg.sender == OWNER); ERC20(tokenAddress).transfer(msg.sender, amtTokens); } function refund(bytes32 oraclizeQueryId) public { // save into memory for cheap access SlotsGameData memory data = slotsData[oraclizeQueryId]; //require that the query time is too slow, bet has not been paid out, and either contract owner or player is calling this function. require(SafeMath.sub(block.timestamp, data.start) >= ORACLIZEQUERYMAXTIME && (msg.sender == OWNER || msg.sender == data.player) && (!data.paidOut) && data.etherReceived <= LIABILITIES && data.etherReceived > 0 && REFUNDSACTIVE); // set contract data slotsData[oraclizeQueryId].paidOut = true; // subtract etherReceived from these two values because the bet is being refunded LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived); // then transfer the original bet to the player. data.player.transfer(data.etherReceived); // finally, log an event saying that the refund has processed. emit Refund(oraclizeQueryId, data.etherReceived); } function play(uint8 credits) public payable { // save for future use / gas efficiency uint256 betPerCredit = msg.value / credits; // require that the game is unpaused, and that the credits being purchased are greater than 0 and less than the allowed amount, default: 100 spins // verify that the bet is less than or equal to the bet limit, so we don't go bankrupt, and that the etherreceived is greater than the minbet. require(!GAMEPAUSED && msg.value >= MINBET_perTX && betPerCredit >= MINBET_perSPIN && credits > 0 && credits <= 224 && SafeMath.mul(betPerCredit, 5000) <= getMaxWin()); // 5000 is the jackpot payout (max win on a roll) // equation for gas to oraclize is: // gas = (some fixed gas amt) + 3270 * credits uint256 gasToSend = INITIALGASFORORACLIZE + (uint256(3270) * credits); EOSBetBankrollInterface(BANKROLLER).payOraclize(oraclize_getPrice('random', gasToSend)); // oraclize_newRandomDSQuery(delay in seconds, bytes of random data, gas for callback function) bytes32 oraclizeQueryId = oraclize_newRandomDSQuery(0, 30, gasToSend); // add the new slots data to a mapping so that the oraclize __callback can use it later slotsData[oraclizeQueryId] = SlotsGameData({ player : msg.sender, paidOut : false, start : block.timestamp, etherReceived : msg.value, credits : credits }); // add the sent value into liabilities. this should NOT go into the bankroll yet // and must be quarantined here to prevent timing attacks LIABILITIES = SafeMath.add(LIABILITIES, msg.value); emit BuyCredits(oraclizeQueryId); } function __callback(bytes32 _queryId, string _result, bytes _proof) public { // get the game data and put into memory SlotsGameData memory data = slotsData[_queryId]; require(msg.sender == oraclize_cbAddress() && !data.paidOut && data.player != address(0) && LIABILITIES >= data.etherReceived); // if the proof has failed, immediately refund the player the original bet. if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0){ if (REFUNDSACTIVE){ // set contract data slotsData[_queryId].paidOut = true; // subtract from liabilities and amount wagered, because this bet is being refunded. LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived); // transfer the original bet back data.player.transfer(data.etherReceived); // log the refund emit Refund(_queryId, data.etherReceived); } // log the ledger proof fail emit LedgerProofFailed(_queryId); } else { // again, this block is almost identical to the previous block in the play(...) function // instead of duplicating documentation, we will just point out the changes from the other block uint256 dialsSpun; uint8 dial1; uint8 dial2; uint8 dial3; uint256[] memory logsData = new uint256[](8); uint256 payout; // must use data.credits instead of credits. for (uint8 i = 0; i < data.credits; i++){ // all dials now use _result, instead of blockhash, this is the main change, and allows Slots to // accomodate bets of any size, free of possible miner interference dialsSpun += 1; dial1 = uint8(uint(keccak256(_result, dialsSpun)) % 64); dialsSpun += 1; dial2 = uint8(uint(keccak256(_result, dialsSpun)) % 64); dialsSpun += 1; dial3 = uint8(uint(keccak256(_result, dialsSpun)) % 64); // dial 1 dial1 = getDial1Type(dial1); // dial 2 dial2 = getDial2Type(dial2); // dial 3 dial3 = getDial3Type(dial3); // determine the payout payout += determinePayout(dial1, dial2, dial3); // assembling log data if (i <= 27){ // in logsData0 logsData[0] += uint256(dial1) * uint256(2) ** (3 * ((3 * (27 - i)) + 2)); logsData[0] += uint256(dial2) * uint256(2) ** (3 * ((3 * (27 - i)) + 1)); logsData[0] += uint256(dial3) * uint256(2) ** (3 * ((3 * (27 - i)))); } else if (i <= 55){ // in logsData1 logsData[1] += uint256(dial1) * uint256(2) ** (3 * ((3 * (55 - i)) + 2)); logsData[1] += uint256(dial2) * uint256(2) ** (3 * ((3 * (55 - i)) + 1)); logsData[1] += uint256(dial3) * uint256(2) ** (3 * ((3 * (55 - i)))); } else if (i <= 83) { // in logsData2 logsData[2] += uint256(dial1) * uint256(2) ** (3 * ((3 * (83 - i)) + 2)); logsData[2] += uint256(dial2) * uint256(2) ** (3 * ((3 * (83 - i)) + 1)); logsData[2] += uint256(dial3) * uint256(2) ** (3 * ((3 * (83 - i)))); } else if (i <= 111) { // in logsData3 logsData[3] += uint256(dial1) * uint256(2) ** (3 * ((3 * (111 - i)) + 2)); logsData[3] += uint256(dial2) * uint256(2) ** (3 * ((3 * (111 - i)) + 1)); logsData[3] += uint256(dial3) * uint256(2) ** (3 * ((3 * (111 - i)))); } else if (i <= 139){ // in logsData4 logsData[4] += uint256(dial1) * uint256(2) ** (3 * ((3 * (139 - i)) + 2)); logsData[4] += uint256(dial2) * uint256(2) ** (3 * ((3 * (139 - i)) + 1)); logsData[4] += uint256(dial3) * uint256(2) ** (3 * ((3 * (139 - i)))); } else if (i <= 167){ // in logsData5 logsData[5] += uint256(dial1) * uint256(2) ** (3 * ((3 * (167 - i)) + 2)); logsData[5] += uint256(dial2) * uint256(2) ** (3 * ((3 * (167 - i)) + 1)); logsData[5] += uint256(dial3) * uint256(2) ** (3 * ((3 * (167 - i)))); } else if (i <= 195){ // in logsData6 logsData[6] += uint256(dial1) * uint256(2) ** (3 * ((3 * (195 - i)) + 2)); logsData[6] += uint256(dial2) * uint256(2) ** (3 * ((3 * (195 - i)) + 1)); logsData[6] += uint256(dial3) * uint256(2) ** (3 * ((3 * (195 - i)))); } else if (i <= 223){ // in logsData7 logsData[7] += uint256(dial1) * uint256(2) ** (3 * ((3 * (223 - i)) + 2)); logsData[7] += uint256(dial2) * uint256(2) ** (3 * ((3 * (223 - i)) + 1)); logsData[7] += uint256(dial3) * uint256(2) ** (3 * ((3 * (223 - i)))); } } // track that these spins were made DIALSSPUN += dialsSpun; // and add the amount wagered AMOUNTWAGERED = SafeMath.add(AMOUNTWAGERED, data.etherReceived); // IMPORTANT: we must change the "paidOut" to TRUE here to prevent reentrancy/other nasty effects. // this was not needed with the previous loop/code block, and is used because variables must be written into storage slotsData[_queryId].paidOut = true; // decrease LIABILITIES when the spins are made LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived); // get the developers cut, and send the rest of the ether received to the bankroller contract uint256 developersCut = data.etherReceived / 100; DEVELOPERSFUND = SafeMath.add(DEVELOPERSFUND, developersCut); EOSBetBankrollInterface(BANKROLLER).receiveEtherFromGameAddress.value(SafeMath.sub(data.etherReceived, developersCut))(); // get the ether to be paid out, and force the bankroller contract to pay out the player uint256 etherPaidout = SafeMath.mul((data.etherReceived / data.credits), payout); EOSBetBankrollInterface(BANKROLLER).payEtherToWinner(etherPaidout, data.player); // log en event with indexed query id emit SlotsLargeBet(_queryId, logsData[0], logsData[1], logsData[2], logsData[3], logsData[4], logsData[5], logsData[6], logsData[7]); } } // HELPER FUNCTIONS TO: // calculate the result of the dials based on the hardcoded slot data: // STOPS REEL#1 REEL#2 REEL#3 /////////////////////////////////////////// // gold ether 0 // 1 // 3 // 1 // // silver ether 1 // 7 // 1 // 6 // // bronze ether 2 // 1 // 7 // 6 // // gold planet 3 // 5 // 7 // 6 // // silverplanet 4 // 9 // 6 // 7 // // bronzeplanet 5 // 9 // 8 // 6 // // ---blank--- 6 // 32 // 32 // 32 // /////////////////////////////////////////// // note that dial1 / 2 / 3 will go from mod 64 to mod 7 in this manner function getDial1Type(uint8 dial1Location) internal pure returns(uint8) { if (dial1Location == 0) { return 0; } else if (dial1Location >= 1 && dial1Location <= 7) { return 1; } else if (dial1Location == 8) { return 2; } else if (dial1Location >= 9 && dial1Location <= 13) { return 3; } else if (dial1Location >= 14 && dial1Location <= 22) { return 4; } else if (dial1Location >= 23 && dial1Location <= 31) { return 5; } else { return 6; } } function getDial2Type(uint8 dial2Location) internal pure returns(uint8) { if (dial2Location >= 0 && dial2Location <= 2) { return 0; } else if (dial2Location == 3) { return 1; } else if (dial2Location >= 4 && dial2Location <= 10) { return 2; } else if (dial2Location >= 11 && dial2Location <= 17) { return 3; } else if (dial2Location >= 18 && dial2Location <= 23) { return 4; } else if (dial2Location >= 24 && dial2Location <= 31) { return 5; } else { return 6; } } function getDial3Type(uint8 dial3Location) internal pure returns(uint8) { if (dial3Location == 0) { return 0; } else if (dial3Location >= 1 && dial3Location <= 6) { return 1; } else if (dial3Location >= 7 && dial3Location <= 12) { return 2; } else if (dial3Location >= 13 && dial3Location <= 18) { return 3; } else if (dial3Location >= 19 && dial3Location <= 25) { return 4; } else if (dial3Location >= 26 && dial3Location <= 31) { return 5; } else { return 6; } } // HELPER FUNCTION TO: // determine the payout given dial locations based on this table // hardcoded payouts data: // LANDS ON // PAYS // //////////////////////////////////////////////// // Bronze E -> Silver E -> Gold E // 5000 // // 3x Gold Ether // 1777 // // 3x Silver Ether // 250 // // 3x Bronze Ether // 250 // // Bronze P -> Silver P -> Gold P // 90 // // 3x any Ether // 70 // // 3x Gold Planet // 50 // // 3x Silver Planet // 25 // // Any Gold P & Silver P & Bronze P // 15 // // 3x Bronze Planet // 10 // // Any 3 planet type // 3 // // Any 3 gold // 3 // // Any 3 silver // 2 // // Any 3 bronze // 2 // // Blank, blank, blank // 1 // // else // 0 // //////////////////////////////////////////////// function determinePayout(uint8 dial1, uint8 dial2, uint8 dial3) internal pure returns(uint256) { if (dial1 == 6 || dial2 == 6 || dial3 == 6){ // all blank if (dial1 == 6 && dial2 == 6 && dial3 == 6) return 1; } else if (dial1 == 5){ // bronze planet -> silver planet -> gold planet if (dial2 == 4 && dial3 == 3) return 90; // one gold planet, one silver planet, one bronze planet, any order! // note: other order covered above, return 90 else if (dial2 == 3 && dial3 == 4) return 15; // all bronze planet else if (dial2 == 5 && dial3 == 5) return 10; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three bronze else if ((dial2 == 2 || dial2 == 5) && (dial3 == 2 || dial3 == 5)) return 2; } else if (dial1 == 4){ // all silver planet if (dial2 == 4 && dial3 == 4) return 25; // one gold planet, one silver planet, one bronze planet, any order! else if ((dial2 == 3 && dial3 == 5) || (dial2 == 5 && dial3 == 3)) return 15; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three silver else if ((dial2 == 1 || dial2 == 4) && (dial3 == 1 || dial3 == 4)) return 2; } else if (dial1 == 3){ // all gold planet if (dial2 == 3 && dial3 == 3) return 50; // one gold planet, one silver planet, one bronze planet, any order! else if ((dial2 == 4 && dial3 == 5) || (dial2 == 5 && dial3 == 4)) return 15; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three gold else if ((dial2 == 0 || dial2 == 3) && (dial3 == 0 || dial3 == 3)) return 3; } else if (dial1 == 2){ if (dial2 == 1 && dial3 == 0) return 5000; // jackpot!!!! // all bronze ether else if (dial2 == 2 && dial3 == 2) return 250; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three bronze else if ((dial2 == 2 || dial2 == 5) && (dial3 == 2 || dial3 == 5)) return 2; } else if (dial1 == 1){ // all silver ether if (dial2 == 1 && dial3 == 1) return 250; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three silver else if ((dial2 == 1 || dial2 == 4) && (dial3 == 1 || dial3 == 4)) return 3; } else if (dial1 == 0){ // all gold ether if (dial2 == 0 && dial3 == 0) return 1777; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three gold else if ((dial2 == 0 || dial2 == 3) && (dial3 == 0 || dial3 == 3)) return 3; } return 0; } }
ERC20Rescue
function ERC20Rescue(address tokenAddress, uint256 amtTokens) public { require (msg.sender == OWNER); ERC20(tokenAddress).transfer(msg.sender, amtTokens); }
// rescue tokens inadvertently sent to the contract address
LineComment
v0.4.21+commit.dfe3193c
bzzr://2d48f2cf6e8bfcc89fb1b8028c0e9f3ac99194db8d859ddd6bcf058cdfd9d462
{ "func_code_index": [ 5243, 5411 ] }
60,062
EOSBetSlots
EOSBetSlots.sol
0x4a3e0c60f7fa67e8b65c401ddbbf7c17fea5fe40
Solidity
EOSBetSlots
contract EOSBetSlots is usingOraclize, EOSBetGameInterface { using SafeMath for *; // events event BuyCredits(bytes32 indexed oraclizeQueryId); event LedgerProofFailed(bytes32 indexed oraclizeQueryId); event Refund(bytes32 indexed oraclizeQueryId, uint256 amount); event SlotsLargeBet(bytes32 indexed oraclizeQueryId, uint256 data1, uint256 data2, uint256 data3, uint256 data4, uint256 data5, uint256 data6, uint256 data7, uint256 data8); event SlotsSmallBet(uint256 data1, uint256 data2, uint256 data3, uint256 data4, uint256 data5, uint256 data6, uint256 data7, uint256 data8); // slots game structure struct SlotsGameData { address player; bool paidOut; uint256 start; uint256 etherReceived; uint8 credits; } mapping (bytes32 => SlotsGameData) public slotsData; // ether in this contract can be in one of two locations: uint256 public LIABILITIES; uint256 public DEVELOPERSFUND; // counters for frontend statistics uint256 public AMOUNTWAGERED; uint256 public DIALSSPUN; // togglable values uint256 public ORACLIZEQUERYMAXTIME; uint256 public MINBET_perSPIN; uint256 public MINBET_perTX; uint256 public ORACLIZEGASPRICE; uint256 public INITIALGASFORORACLIZE; uint16 public MAXWIN_inTHOUSANDTHPERCENTS; // togglable functionality of contract bool public GAMEPAUSED; bool public REFUNDSACTIVE; // owner of contract address public OWNER; // bankroller address address public BANKROLLER; // constructor function EOSBetSlots() public { // ledger proof is ALWAYS verified on-chain oraclize_setProof(proofType_Ledger); // gas prices for oraclize call back, can be changed oraclize_setCustomGasPrice(8000000000); ORACLIZEGASPRICE = 8000000000; INITIALGASFORORACLIZE = 225000; AMOUNTWAGERED = 0; DIALSSPUN = 0; GAMEPAUSED = false; REFUNDSACTIVE = true; ORACLIZEQUERYMAXTIME = 6 hours; MINBET_perSPIN = 2 finney; // currently, this is ~40-50c a spin, which is pretty average slots. This is changeable by OWNER MINBET_perTX = 10 finney; MAXWIN_inTHOUSANDTHPERCENTS = 333; // 333/1000 so a jackpot can take 33% of bankroll (extremely rare) OWNER = msg.sender; } //////////////////////////////////// // INTERFACE CONTACT FUNCTIONS //////////////////////////////////// function payDevelopersFund(address developer) public { require(msg.sender == BANKROLLER); uint256 devFund = DEVELOPERSFUND; DEVELOPERSFUND = 0; developer.transfer(devFund); } // just a function to receive eth, only allow the bankroll to use this function receivePaymentForOraclize() payable public { require(msg.sender == BANKROLLER); } //////////////////////////////////// // VIEW FUNCTIONS //////////////////////////////////// function getMaxWin() public view returns(uint256){ return (SafeMath.mul(EOSBetBankrollInterface(BANKROLLER).getBankroll(), MAXWIN_inTHOUSANDTHPERCENTS) / 1000); } //////////////////////////////////// // OWNER ONLY FUNCTIONS //////////////////////////////////// // WARNING!!!!! Can only set this function once! function setBankrollerContractOnce(address bankrollAddress) public { // require that BANKROLLER address == 0x0 (address not set yet), and coming from owner. require(msg.sender == OWNER && BANKROLLER == address(0)); // check here to make sure that the bankroll contract is legitimate // just make sure that calling the bankroll contract getBankroll() returns non-zero require(EOSBetBankrollInterface(bankrollAddress).getBankroll() != 0); BANKROLLER = bankrollAddress; } function transferOwnership(address newOwner) public { require(msg.sender == OWNER); OWNER = newOwner; } function setOraclizeQueryMaxTime(uint256 newTime) public { require(msg.sender == OWNER); ORACLIZEQUERYMAXTIME = newTime; } // store the gas price as a storage variable for easy reference, // and thne change the gas price using the proper oraclize function function setOraclizeQueryGasPrice(uint256 gasPrice) public { require(msg.sender == OWNER); ORACLIZEGASPRICE = gasPrice; oraclize_setCustomGasPrice(gasPrice); } // should be ~160,000 to save eth function setInitialGasForOraclize(uint256 gasAmt) public { require(msg.sender == OWNER); INITIALGASFORORACLIZE = gasAmt; } function setGamePaused(bool paused) public { require(msg.sender == OWNER); GAMEPAUSED = paused; } function setRefundsActive(bool active) public { require(msg.sender == OWNER); REFUNDSACTIVE = active; } function setMinBetPerSpin(uint256 minBet) public { require(msg.sender == OWNER && minBet > 1000); MINBET_perSPIN = minBet; } function setMinBetPerTx(uint256 minBet) public { require(msg.sender == OWNER && minBet > 1000); MINBET_perTX = minBet; } function setMaxwin(uint16 newMaxWinInThousandthPercents) public { require(msg.sender == OWNER && newMaxWinInThousandthPercents <= 333); // cannot set max win greater than 1/3 of the bankroll (a jackpot is very rare) MAXWIN_inTHOUSANDTHPERCENTS = newMaxWinInThousandthPercents; } // rescue tokens inadvertently sent to the contract address function ERC20Rescue(address tokenAddress, uint256 amtTokens) public { require (msg.sender == OWNER); ERC20(tokenAddress).transfer(msg.sender, amtTokens); } function refund(bytes32 oraclizeQueryId) public { // save into memory for cheap access SlotsGameData memory data = slotsData[oraclizeQueryId]; //require that the query time is too slow, bet has not been paid out, and either contract owner or player is calling this function. require(SafeMath.sub(block.timestamp, data.start) >= ORACLIZEQUERYMAXTIME && (msg.sender == OWNER || msg.sender == data.player) && (!data.paidOut) && data.etherReceived <= LIABILITIES && data.etherReceived > 0 && REFUNDSACTIVE); // set contract data slotsData[oraclizeQueryId].paidOut = true; // subtract etherReceived from these two values because the bet is being refunded LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived); // then transfer the original bet to the player. data.player.transfer(data.etherReceived); // finally, log an event saying that the refund has processed. emit Refund(oraclizeQueryId, data.etherReceived); } function play(uint8 credits) public payable { // save for future use / gas efficiency uint256 betPerCredit = msg.value / credits; // require that the game is unpaused, and that the credits being purchased are greater than 0 and less than the allowed amount, default: 100 spins // verify that the bet is less than or equal to the bet limit, so we don't go bankrupt, and that the etherreceived is greater than the minbet. require(!GAMEPAUSED && msg.value >= MINBET_perTX && betPerCredit >= MINBET_perSPIN && credits > 0 && credits <= 224 && SafeMath.mul(betPerCredit, 5000) <= getMaxWin()); // 5000 is the jackpot payout (max win on a roll) // equation for gas to oraclize is: // gas = (some fixed gas amt) + 3270 * credits uint256 gasToSend = INITIALGASFORORACLIZE + (uint256(3270) * credits); EOSBetBankrollInterface(BANKROLLER).payOraclize(oraclize_getPrice('random', gasToSend)); // oraclize_newRandomDSQuery(delay in seconds, bytes of random data, gas for callback function) bytes32 oraclizeQueryId = oraclize_newRandomDSQuery(0, 30, gasToSend); // add the new slots data to a mapping so that the oraclize __callback can use it later slotsData[oraclizeQueryId] = SlotsGameData({ player : msg.sender, paidOut : false, start : block.timestamp, etherReceived : msg.value, credits : credits }); // add the sent value into liabilities. this should NOT go into the bankroll yet // and must be quarantined here to prevent timing attacks LIABILITIES = SafeMath.add(LIABILITIES, msg.value); emit BuyCredits(oraclizeQueryId); } function __callback(bytes32 _queryId, string _result, bytes _proof) public { // get the game data and put into memory SlotsGameData memory data = slotsData[_queryId]; require(msg.sender == oraclize_cbAddress() && !data.paidOut && data.player != address(0) && LIABILITIES >= data.etherReceived); // if the proof has failed, immediately refund the player the original bet. if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0){ if (REFUNDSACTIVE){ // set contract data slotsData[_queryId].paidOut = true; // subtract from liabilities and amount wagered, because this bet is being refunded. LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived); // transfer the original bet back data.player.transfer(data.etherReceived); // log the refund emit Refund(_queryId, data.etherReceived); } // log the ledger proof fail emit LedgerProofFailed(_queryId); } else { // again, this block is almost identical to the previous block in the play(...) function // instead of duplicating documentation, we will just point out the changes from the other block uint256 dialsSpun; uint8 dial1; uint8 dial2; uint8 dial3; uint256[] memory logsData = new uint256[](8); uint256 payout; // must use data.credits instead of credits. for (uint8 i = 0; i < data.credits; i++){ // all dials now use _result, instead of blockhash, this is the main change, and allows Slots to // accomodate bets of any size, free of possible miner interference dialsSpun += 1; dial1 = uint8(uint(keccak256(_result, dialsSpun)) % 64); dialsSpun += 1; dial2 = uint8(uint(keccak256(_result, dialsSpun)) % 64); dialsSpun += 1; dial3 = uint8(uint(keccak256(_result, dialsSpun)) % 64); // dial 1 dial1 = getDial1Type(dial1); // dial 2 dial2 = getDial2Type(dial2); // dial 3 dial3 = getDial3Type(dial3); // determine the payout payout += determinePayout(dial1, dial2, dial3); // assembling log data if (i <= 27){ // in logsData0 logsData[0] += uint256(dial1) * uint256(2) ** (3 * ((3 * (27 - i)) + 2)); logsData[0] += uint256(dial2) * uint256(2) ** (3 * ((3 * (27 - i)) + 1)); logsData[0] += uint256(dial3) * uint256(2) ** (3 * ((3 * (27 - i)))); } else if (i <= 55){ // in logsData1 logsData[1] += uint256(dial1) * uint256(2) ** (3 * ((3 * (55 - i)) + 2)); logsData[1] += uint256(dial2) * uint256(2) ** (3 * ((3 * (55 - i)) + 1)); logsData[1] += uint256(dial3) * uint256(2) ** (3 * ((3 * (55 - i)))); } else if (i <= 83) { // in logsData2 logsData[2] += uint256(dial1) * uint256(2) ** (3 * ((3 * (83 - i)) + 2)); logsData[2] += uint256(dial2) * uint256(2) ** (3 * ((3 * (83 - i)) + 1)); logsData[2] += uint256(dial3) * uint256(2) ** (3 * ((3 * (83 - i)))); } else if (i <= 111) { // in logsData3 logsData[3] += uint256(dial1) * uint256(2) ** (3 * ((3 * (111 - i)) + 2)); logsData[3] += uint256(dial2) * uint256(2) ** (3 * ((3 * (111 - i)) + 1)); logsData[3] += uint256(dial3) * uint256(2) ** (3 * ((3 * (111 - i)))); } else if (i <= 139){ // in logsData4 logsData[4] += uint256(dial1) * uint256(2) ** (3 * ((3 * (139 - i)) + 2)); logsData[4] += uint256(dial2) * uint256(2) ** (3 * ((3 * (139 - i)) + 1)); logsData[4] += uint256(dial3) * uint256(2) ** (3 * ((3 * (139 - i)))); } else if (i <= 167){ // in logsData5 logsData[5] += uint256(dial1) * uint256(2) ** (3 * ((3 * (167 - i)) + 2)); logsData[5] += uint256(dial2) * uint256(2) ** (3 * ((3 * (167 - i)) + 1)); logsData[5] += uint256(dial3) * uint256(2) ** (3 * ((3 * (167 - i)))); } else if (i <= 195){ // in logsData6 logsData[6] += uint256(dial1) * uint256(2) ** (3 * ((3 * (195 - i)) + 2)); logsData[6] += uint256(dial2) * uint256(2) ** (3 * ((3 * (195 - i)) + 1)); logsData[6] += uint256(dial3) * uint256(2) ** (3 * ((3 * (195 - i)))); } else if (i <= 223){ // in logsData7 logsData[7] += uint256(dial1) * uint256(2) ** (3 * ((3 * (223 - i)) + 2)); logsData[7] += uint256(dial2) * uint256(2) ** (3 * ((3 * (223 - i)) + 1)); logsData[7] += uint256(dial3) * uint256(2) ** (3 * ((3 * (223 - i)))); } } // track that these spins were made DIALSSPUN += dialsSpun; // and add the amount wagered AMOUNTWAGERED = SafeMath.add(AMOUNTWAGERED, data.etherReceived); // IMPORTANT: we must change the "paidOut" to TRUE here to prevent reentrancy/other nasty effects. // this was not needed with the previous loop/code block, and is used because variables must be written into storage slotsData[_queryId].paidOut = true; // decrease LIABILITIES when the spins are made LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived); // get the developers cut, and send the rest of the ether received to the bankroller contract uint256 developersCut = data.etherReceived / 100; DEVELOPERSFUND = SafeMath.add(DEVELOPERSFUND, developersCut); EOSBetBankrollInterface(BANKROLLER).receiveEtherFromGameAddress.value(SafeMath.sub(data.etherReceived, developersCut))(); // get the ether to be paid out, and force the bankroller contract to pay out the player uint256 etherPaidout = SafeMath.mul((data.etherReceived / data.credits), payout); EOSBetBankrollInterface(BANKROLLER).payEtherToWinner(etherPaidout, data.player); // log en event with indexed query id emit SlotsLargeBet(_queryId, logsData[0], logsData[1], logsData[2], logsData[3], logsData[4], logsData[5], logsData[6], logsData[7]); } } // HELPER FUNCTIONS TO: // calculate the result of the dials based on the hardcoded slot data: // STOPS REEL#1 REEL#2 REEL#3 /////////////////////////////////////////// // gold ether 0 // 1 // 3 // 1 // // silver ether 1 // 7 // 1 // 6 // // bronze ether 2 // 1 // 7 // 6 // // gold planet 3 // 5 // 7 // 6 // // silverplanet 4 // 9 // 6 // 7 // // bronzeplanet 5 // 9 // 8 // 6 // // ---blank--- 6 // 32 // 32 // 32 // /////////////////////////////////////////// // note that dial1 / 2 / 3 will go from mod 64 to mod 7 in this manner function getDial1Type(uint8 dial1Location) internal pure returns(uint8) { if (dial1Location == 0) { return 0; } else if (dial1Location >= 1 && dial1Location <= 7) { return 1; } else if (dial1Location == 8) { return 2; } else if (dial1Location >= 9 && dial1Location <= 13) { return 3; } else if (dial1Location >= 14 && dial1Location <= 22) { return 4; } else if (dial1Location >= 23 && dial1Location <= 31) { return 5; } else { return 6; } } function getDial2Type(uint8 dial2Location) internal pure returns(uint8) { if (dial2Location >= 0 && dial2Location <= 2) { return 0; } else if (dial2Location == 3) { return 1; } else if (dial2Location >= 4 && dial2Location <= 10) { return 2; } else if (dial2Location >= 11 && dial2Location <= 17) { return 3; } else if (dial2Location >= 18 && dial2Location <= 23) { return 4; } else if (dial2Location >= 24 && dial2Location <= 31) { return 5; } else { return 6; } } function getDial3Type(uint8 dial3Location) internal pure returns(uint8) { if (dial3Location == 0) { return 0; } else if (dial3Location >= 1 && dial3Location <= 6) { return 1; } else if (dial3Location >= 7 && dial3Location <= 12) { return 2; } else if (dial3Location >= 13 && dial3Location <= 18) { return 3; } else if (dial3Location >= 19 && dial3Location <= 25) { return 4; } else if (dial3Location >= 26 && dial3Location <= 31) { return 5; } else { return 6; } } // HELPER FUNCTION TO: // determine the payout given dial locations based on this table // hardcoded payouts data: // LANDS ON // PAYS // //////////////////////////////////////////////// // Bronze E -> Silver E -> Gold E // 5000 // // 3x Gold Ether // 1777 // // 3x Silver Ether // 250 // // 3x Bronze Ether // 250 // // Bronze P -> Silver P -> Gold P // 90 // // 3x any Ether // 70 // // 3x Gold Planet // 50 // // 3x Silver Planet // 25 // // Any Gold P & Silver P & Bronze P // 15 // // 3x Bronze Planet // 10 // // Any 3 planet type // 3 // // Any 3 gold // 3 // // Any 3 silver // 2 // // Any 3 bronze // 2 // // Blank, blank, blank // 1 // // else // 0 // //////////////////////////////////////////////// function determinePayout(uint8 dial1, uint8 dial2, uint8 dial3) internal pure returns(uint256) { if (dial1 == 6 || dial2 == 6 || dial3 == 6){ // all blank if (dial1 == 6 && dial2 == 6 && dial3 == 6) return 1; } else if (dial1 == 5){ // bronze planet -> silver planet -> gold planet if (dial2 == 4 && dial3 == 3) return 90; // one gold planet, one silver planet, one bronze planet, any order! // note: other order covered above, return 90 else if (dial2 == 3 && dial3 == 4) return 15; // all bronze planet else if (dial2 == 5 && dial3 == 5) return 10; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three bronze else if ((dial2 == 2 || dial2 == 5) && (dial3 == 2 || dial3 == 5)) return 2; } else if (dial1 == 4){ // all silver planet if (dial2 == 4 && dial3 == 4) return 25; // one gold planet, one silver planet, one bronze planet, any order! else if ((dial2 == 3 && dial3 == 5) || (dial2 == 5 && dial3 == 3)) return 15; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three silver else if ((dial2 == 1 || dial2 == 4) && (dial3 == 1 || dial3 == 4)) return 2; } else if (dial1 == 3){ // all gold planet if (dial2 == 3 && dial3 == 3) return 50; // one gold planet, one silver planet, one bronze planet, any order! else if ((dial2 == 4 && dial3 == 5) || (dial2 == 5 && dial3 == 4)) return 15; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three gold else if ((dial2 == 0 || dial2 == 3) && (dial3 == 0 || dial3 == 3)) return 3; } else if (dial1 == 2){ if (dial2 == 1 && dial3 == 0) return 5000; // jackpot!!!! // all bronze ether else if (dial2 == 2 && dial3 == 2) return 250; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three bronze else if ((dial2 == 2 || dial2 == 5) && (dial3 == 2 || dial3 == 5)) return 2; } else if (dial1 == 1){ // all silver ether if (dial2 == 1 && dial3 == 1) return 250; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three silver else if ((dial2 == 1 || dial2 == 4) && (dial3 == 1 || dial3 == 4)) return 3; } else if (dial1 == 0){ // all gold ether if (dial2 == 0 && dial3 == 0) return 1777; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three gold else if ((dial2 == 0 || dial2 == 3) && (dial3 == 0 || dial3 == 3)) return 3; } return 0; } }
getDial1Type
function getDial1Type(uint8 dial1Location) internal pure returns(uint8) { if (dial1Location == 0) { return 0; } else if (dial1Location >= 1 && dial1Location <= 7) { return 1; } else if (dial1Location == 8) { return 2; } else if (dial1Location >= 9 && dial1Location <= 13) { return 3; } else if (dial1Location >= 14 && dial1Location <= 22) { return 4; } else if (dial1Location >= 23 && dial1Location <= 31) { return 5; } else { return 6; } }
// note that dial1 / 2 / 3 will go from mod 64 to mod 7 in this manner
LineComment
v0.4.21+commit.dfe3193c
bzzr://2d48f2cf6e8bfcc89fb1b8028c0e9f3ac99194db8d859ddd6bcf058cdfd9d462
{ "func_code_index": [ 14540, 15072 ] }
60,063
EOSBetSlots
EOSBetSlots.sol
0x4a3e0c60f7fa67e8b65c401ddbbf7c17fea5fe40
Solidity
EOSBetSlots
contract EOSBetSlots is usingOraclize, EOSBetGameInterface { using SafeMath for *; // events event BuyCredits(bytes32 indexed oraclizeQueryId); event LedgerProofFailed(bytes32 indexed oraclizeQueryId); event Refund(bytes32 indexed oraclizeQueryId, uint256 amount); event SlotsLargeBet(bytes32 indexed oraclizeQueryId, uint256 data1, uint256 data2, uint256 data3, uint256 data4, uint256 data5, uint256 data6, uint256 data7, uint256 data8); event SlotsSmallBet(uint256 data1, uint256 data2, uint256 data3, uint256 data4, uint256 data5, uint256 data6, uint256 data7, uint256 data8); // slots game structure struct SlotsGameData { address player; bool paidOut; uint256 start; uint256 etherReceived; uint8 credits; } mapping (bytes32 => SlotsGameData) public slotsData; // ether in this contract can be in one of two locations: uint256 public LIABILITIES; uint256 public DEVELOPERSFUND; // counters for frontend statistics uint256 public AMOUNTWAGERED; uint256 public DIALSSPUN; // togglable values uint256 public ORACLIZEQUERYMAXTIME; uint256 public MINBET_perSPIN; uint256 public MINBET_perTX; uint256 public ORACLIZEGASPRICE; uint256 public INITIALGASFORORACLIZE; uint16 public MAXWIN_inTHOUSANDTHPERCENTS; // togglable functionality of contract bool public GAMEPAUSED; bool public REFUNDSACTIVE; // owner of contract address public OWNER; // bankroller address address public BANKROLLER; // constructor function EOSBetSlots() public { // ledger proof is ALWAYS verified on-chain oraclize_setProof(proofType_Ledger); // gas prices for oraclize call back, can be changed oraclize_setCustomGasPrice(8000000000); ORACLIZEGASPRICE = 8000000000; INITIALGASFORORACLIZE = 225000; AMOUNTWAGERED = 0; DIALSSPUN = 0; GAMEPAUSED = false; REFUNDSACTIVE = true; ORACLIZEQUERYMAXTIME = 6 hours; MINBET_perSPIN = 2 finney; // currently, this is ~40-50c a spin, which is pretty average slots. This is changeable by OWNER MINBET_perTX = 10 finney; MAXWIN_inTHOUSANDTHPERCENTS = 333; // 333/1000 so a jackpot can take 33% of bankroll (extremely rare) OWNER = msg.sender; } //////////////////////////////////// // INTERFACE CONTACT FUNCTIONS //////////////////////////////////// function payDevelopersFund(address developer) public { require(msg.sender == BANKROLLER); uint256 devFund = DEVELOPERSFUND; DEVELOPERSFUND = 0; developer.transfer(devFund); } // just a function to receive eth, only allow the bankroll to use this function receivePaymentForOraclize() payable public { require(msg.sender == BANKROLLER); } //////////////////////////////////// // VIEW FUNCTIONS //////////////////////////////////// function getMaxWin() public view returns(uint256){ return (SafeMath.mul(EOSBetBankrollInterface(BANKROLLER).getBankroll(), MAXWIN_inTHOUSANDTHPERCENTS) / 1000); } //////////////////////////////////// // OWNER ONLY FUNCTIONS //////////////////////////////////// // WARNING!!!!! Can only set this function once! function setBankrollerContractOnce(address bankrollAddress) public { // require that BANKROLLER address == 0x0 (address not set yet), and coming from owner. require(msg.sender == OWNER && BANKROLLER == address(0)); // check here to make sure that the bankroll contract is legitimate // just make sure that calling the bankroll contract getBankroll() returns non-zero require(EOSBetBankrollInterface(bankrollAddress).getBankroll() != 0); BANKROLLER = bankrollAddress; } function transferOwnership(address newOwner) public { require(msg.sender == OWNER); OWNER = newOwner; } function setOraclizeQueryMaxTime(uint256 newTime) public { require(msg.sender == OWNER); ORACLIZEQUERYMAXTIME = newTime; } // store the gas price as a storage variable for easy reference, // and thne change the gas price using the proper oraclize function function setOraclizeQueryGasPrice(uint256 gasPrice) public { require(msg.sender == OWNER); ORACLIZEGASPRICE = gasPrice; oraclize_setCustomGasPrice(gasPrice); } // should be ~160,000 to save eth function setInitialGasForOraclize(uint256 gasAmt) public { require(msg.sender == OWNER); INITIALGASFORORACLIZE = gasAmt; } function setGamePaused(bool paused) public { require(msg.sender == OWNER); GAMEPAUSED = paused; } function setRefundsActive(bool active) public { require(msg.sender == OWNER); REFUNDSACTIVE = active; } function setMinBetPerSpin(uint256 minBet) public { require(msg.sender == OWNER && minBet > 1000); MINBET_perSPIN = minBet; } function setMinBetPerTx(uint256 minBet) public { require(msg.sender == OWNER && minBet > 1000); MINBET_perTX = minBet; } function setMaxwin(uint16 newMaxWinInThousandthPercents) public { require(msg.sender == OWNER && newMaxWinInThousandthPercents <= 333); // cannot set max win greater than 1/3 of the bankroll (a jackpot is very rare) MAXWIN_inTHOUSANDTHPERCENTS = newMaxWinInThousandthPercents; } // rescue tokens inadvertently sent to the contract address function ERC20Rescue(address tokenAddress, uint256 amtTokens) public { require (msg.sender == OWNER); ERC20(tokenAddress).transfer(msg.sender, amtTokens); } function refund(bytes32 oraclizeQueryId) public { // save into memory for cheap access SlotsGameData memory data = slotsData[oraclizeQueryId]; //require that the query time is too slow, bet has not been paid out, and either contract owner or player is calling this function. require(SafeMath.sub(block.timestamp, data.start) >= ORACLIZEQUERYMAXTIME && (msg.sender == OWNER || msg.sender == data.player) && (!data.paidOut) && data.etherReceived <= LIABILITIES && data.etherReceived > 0 && REFUNDSACTIVE); // set contract data slotsData[oraclizeQueryId].paidOut = true; // subtract etherReceived from these two values because the bet is being refunded LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived); // then transfer the original bet to the player. data.player.transfer(data.etherReceived); // finally, log an event saying that the refund has processed. emit Refund(oraclizeQueryId, data.etherReceived); } function play(uint8 credits) public payable { // save for future use / gas efficiency uint256 betPerCredit = msg.value / credits; // require that the game is unpaused, and that the credits being purchased are greater than 0 and less than the allowed amount, default: 100 spins // verify that the bet is less than or equal to the bet limit, so we don't go bankrupt, and that the etherreceived is greater than the minbet. require(!GAMEPAUSED && msg.value >= MINBET_perTX && betPerCredit >= MINBET_perSPIN && credits > 0 && credits <= 224 && SafeMath.mul(betPerCredit, 5000) <= getMaxWin()); // 5000 is the jackpot payout (max win on a roll) // equation for gas to oraclize is: // gas = (some fixed gas amt) + 3270 * credits uint256 gasToSend = INITIALGASFORORACLIZE + (uint256(3270) * credits); EOSBetBankrollInterface(BANKROLLER).payOraclize(oraclize_getPrice('random', gasToSend)); // oraclize_newRandomDSQuery(delay in seconds, bytes of random data, gas for callback function) bytes32 oraclizeQueryId = oraclize_newRandomDSQuery(0, 30, gasToSend); // add the new slots data to a mapping so that the oraclize __callback can use it later slotsData[oraclizeQueryId] = SlotsGameData({ player : msg.sender, paidOut : false, start : block.timestamp, etherReceived : msg.value, credits : credits }); // add the sent value into liabilities. this should NOT go into the bankroll yet // and must be quarantined here to prevent timing attacks LIABILITIES = SafeMath.add(LIABILITIES, msg.value); emit BuyCredits(oraclizeQueryId); } function __callback(bytes32 _queryId, string _result, bytes _proof) public { // get the game data and put into memory SlotsGameData memory data = slotsData[_queryId]; require(msg.sender == oraclize_cbAddress() && !data.paidOut && data.player != address(0) && LIABILITIES >= data.etherReceived); // if the proof has failed, immediately refund the player the original bet. if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0){ if (REFUNDSACTIVE){ // set contract data slotsData[_queryId].paidOut = true; // subtract from liabilities and amount wagered, because this bet is being refunded. LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived); // transfer the original bet back data.player.transfer(data.etherReceived); // log the refund emit Refund(_queryId, data.etherReceived); } // log the ledger proof fail emit LedgerProofFailed(_queryId); } else { // again, this block is almost identical to the previous block in the play(...) function // instead of duplicating documentation, we will just point out the changes from the other block uint256 dialsSpun; uint8 dial1; uint8 dial2; uint8 dial3; uint256[] memory logsData = new uint256[](8); uint256 payout; // must use data.credits instead of credits. for (uint8 i = 0; i < data.credits; i++){ // all dials now use _result, instead of blockhash, this is the main change, and allows Slots to // accomodate bets of any size, free of possible miner interference dialsSpun += 1; dial1 = uint8(uint(keccak256(_result, dialsSpun)) % 64); dialsSpun += 1; dial2 = uint8(uint(keccak256(_result, dialsSpun)) % 64); dialsSpun += 1; dial3 = uint8(uint(keccak256(_result, dialsSpun)) % 64); // dial 1 dial1 = getDial1Type(dial1); // dial 2 dial2 = getDial2Type(dial2); // dial 3 dial3 = getDial3Type(dial3); // determine the payout payout += determinePayout(dial1, dial2, dial3); // assembling log data if (i <= 27){ // in logsData0 logsData[0] += uint256(dial1) * uint256(2) ** (3 * ((3 * (27 - i)) + 2)); logsData[0] += uint256(dial2) * uint256(2) ** (3 * ((3 * (27 - i)) + 1)); logsData[0] += uint256(dial3) * uint256(2) ** (3 * ((3 * (27 - i)))); } else if (i <= 55){ // in logsData1 logsData[1] += uint256(dial1) * uint256(2) ** (3 * ((3 * (55 - i)) + 2)); logsData[1] += uint256(dial2) * uint256(2) ** (3 * ((3 * (55 - i)) + 1)); logsData[1] += uint256(dial3) * uint256(2) ** (3 * ((3 * (55 - i)))); } else if (i <= 83) { // in logsData2 logsData[2] += uint256(dial1) * uint256(2) ** (3 * ((3 * (83 - i)) + 2)); logsData[2] += uint256(dial2) * uint256(2) ** (3 * ((3 * (83 - i)) + 1)); logsData[2] += uint256(dial3) * uint256(2) ** (3 * ((3 * (83 - i)))); } else if (i <= 111) { // in logsData3 logsData[3] += uint256(dial1) * uint256(2) ** (3 * ((3 * (111 - i)) + 2)); logsData[3] += uint256(dial2) * uint256(2) ** (3 * ((3 * (111 - i)) + 1)); logsData[3] += uint256(dial3) * uint256(2) ** (3 * ((3 * (111 - i)))); } else if (i <= 139){ // in logsData4 logsData[4] += uint256(dial1) * uint256(2) ** (3 * ((3 * (139 - i)) + 2)); logsData[4] += uint256(dial2) * uint256(2) ** (3 * ((3 * (139 - i)) + 1)); logsData[4] += uint256(dial3) * uint256(2) ** (3 * ((3 * (139 - i)))); } else if (i <= 167){ // in logsData5 logsData[5] += uint256(dial1) * uint256(2) ** (3 * ((3 * (167 - i)) + 2)); logsData[5] += uint256(dial2) * uint256(2) ** (3 * ((3 * (167 - i)) + 1)); logsData[5] += uint256(dial3) * uint256(2) ** (3 * ((3 * (167 - i)))); } else if (i <= 195){ // in logsData6 logsData[6] += uint256(dial1) * uint256(2) ** (3 * ((3 * (195 - i)) + 2)); logsData[6] += uint256(dial2) * uint256(2) ** (3 * ((3 * (195 - i)) + 1)); logsData[6] += uint256(dial3) * uint256(2) ** (3 * ((3 * (195 - i)))); } else if (i <= 223){ // in logsData7 logsData[7] += uint256(dial1) * uint256(2) ** (3 * ((3 * (223 - i)) + 2)); logsData[7] += uint256(dial2) * uint256(2) ** (3 * ((3 * (223 - i)) + 1)); logsData[7] += uint256(dial3) * uint256(2) ** (3 * ((3 * (223 - i)))); } } // track that these spins were made DIALSSPUN += dialsSpun; // and add the amount wagered AMOUNTWAGERED = SafeMath.add(AMOUNTWAGERED, data.etherReceived); // IMPORTANT: we must change the "paidOut" to TRUE here to prevent reentrancy/other nasty effects. // this was not needed with the previous loop/code block, and is used because variables must be written into storage slotsData[_queryId].paidOut = true; // decrease LIABILITIES when the spins are made LIABILITIES = SafeMath.sub(LIABILITIES, data.etherReceived); // get the developers cut, and send the rest of the ether received to the bankroller contract uint256 developersCut = data.etherReceived / 100; DEVELOPERSFUND = SafeMath.add(DEVELOPERSFUND, developersCut); EOSBetBankrollInterface(BANKROLLER).receiveEtherFromGameAddress.value(SafeMath.sub(data.etherReceived, developersCut))(); // get the ether to be paid out, and force the bankroller contract to pay out the player uint256 etherPaidout = SafeMath.mul((data.etherReceived / data.credits), payout); EOSBetBankrollInterface(BANKROLLER).payEtherToWinner(etherPaidout, data.player); // log en event with indexed query id emit SlotsLargeBet(_queryId, logsData[0], logsData[1], logsData[2], logsData[3], logsData[4], logsData[5], logsData[6], logsData[7]); } } // HELPER FUNCTIONS TO: // calculate the result of the dials based on the hardcoded slot data: // STOPS REEL#1 REEL#2 REEL#3 /////////////////////////////////////////// // gold ether 0 // 1 // 3 // 1 // // silver ether 1 // 7 // 1 // 6 // // bronze ether 2 // 1 // 7 // 6 // // gold planet 3 // 5 // 7 // 6 // // silverplanet 4 // 9 // 6 // 7 // // bronzeplanet 5 // 9 // 8 // 6 // // ---blank--- 6 // 32 // 32 // 32 // /////////////////////////////////////////// // note that dial1 / 2 / 3 will go from mod 64 to mod 7 in this manner function getDial1Type(uint8 dial1Location) internal pure returns(uint8) { if (dial1Location == 0) { return 0; } else if (dial1Location >= 1 && dial1Location <= 7) { return 1; } else if (dial1Location == 8) { return 2; } else if (dial1Location >= 9 && dial1Location <= 13) { return 3; } else if (dial1Location >= 14 && dial1Location <= 22) { return 4; } else if (dial1Location >= 23 && dial1Location <= 31) { return 5; } else { return 6; } } function getDial2Type(uint8 dial2Location) internal pure returns(uint8) { if (dial2Location >= 0 && dial2Location <= 2) { return 0; } else if (dial2Location == 3) { return 1; } else if (dial2Location >= 4 && dial2Location <= 10) { return 2; } else if (dial2Location >= 11 && dial2Location <= 17) { return 3; } else if (dial2Location >= 18 && dial2Location <= 23) { return 4; } else if (dial2Location >= 24 && dial2Location <= 31) { return 5; } else { return 6; } } function getDial3Type(uint8 dial3Location) internal pure returns(uint8) { if (dial3Location == 0) { return 0; } else if (dial3Location >= 1 && dial3Location <= 6) { return 1; } else if (dial3Location >= 7 && dial3Location <= 12) { return 2; } else if (dial3Location >= 13 && dial3Location <= 18) { return 3; } else if (dial3Location >= 19 && dial3Location <= 25) { return 4; } else if (dial3Location >= 26 && dial3Location <= 31) { return 5; } else { return 6; } } // HELPER FUNCTION TO: // determine the payout given dial locations based on this table // hardcoded payouts data: // LANDS ON // PAYS // //////////////////////////////////////////////// // Bronze E -> Silver E -> Gold E // 5000 // // 3x Gold Ether // 1777 // // 3x Silver Ether // 250 // // 3x Bronze Ether // 250 // // Bronze P -> Silver P -> Gold P // 90 // // 3x any Ether // 70 // // 3x Gold Planet // 50 // // 3x Silver Planet // 25 // // Any Gold P & Silver P & Bronze P // 15 // // 3x Bronze Planet // 10 // // Any 3 planet type // 3 // // Any 3 gold // 3 // // Any 3 silver // 2 // // Any 3 bronze // 2 // // Blank, blank, blank // 1 // // else // 0 // //////////////////////////////////////////////// function determinePayout(uint8 dial1, uint8 dial2, uint8 dial3) internal pure returns(uint256) { if (dial1 == 6 || dial2 == 6 || dial3 == 6){ // all blank if (dial1 == 6 && dial2 == 6 && dial3 == 6) return 1; } else if (dial1 == 5){ // bronze planet -> silver planet -> gold planet if (dial2 == 4 && dial3 == 3) return 90; // one gold planet, one silver planet, one bronze planet, any order! // note: other order covered above, return 90 else if (dial2 == 3 && dial3 == 4) return 15; // all bronze planet else if (dial2 == 5 && dial3 == 5) return 10; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three bronze else if ((dial2 == 2 || dial2 == 5) && (dial3 == 2 || dial3 == 5)) return 2; } else if (dial1 == 4){ // all silver planet if (dial2 == 4 && dial3 == 4) return 25; // one gold planet, one silver planet, one bronze planet, any order! else if ((dial2 == 3 && dial3 == 5) || (dial2 == 5 && dial3 == 3)) return 15; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three silver else if ((dial2 == 1 || dial2 == 4) && (dial3 == 1 || dial3 == 4)) return 2; } else if (dial1 == 3){ // all gold planet if (dial2 == 3 && dial3 == 3) return 50; // one gold planet, one silver planet, one bronze planet, any order! else if ((dial2 == 4 && dial3 == 5) || (dial2 == 5 && dial3 == 4)) return 15; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three gold else if ((dial2 == 0 || dial2 == 3) && (dial3 == 0 || dial3 == 3)) return 3; } else if (dial1 == 2){ if (dial2 == 1 && dial3 == 0) return 5000; // jackpot!!!! // all bronze ether else if (dial2 == 2 && dial3 == 2) return 250; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three bronze else if ((dial2 == 2 || dial2 == 5) && (dial3 == 2 || dial3 == 5)) return 2; } else if (dial1 == 1){ // all silver ether if (dial2 == 1 && dial3 == 1) return 250; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three silver else if ((dial2 == 1 || dial2 == 4) && (dial3 == 1 || dial3 == 4)) return 3; } else if (dial1 == 0){ // all gold ether if (dial2 == 0 && dial3 == 0) return 1777; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three gold else if ((dial2 == 0 || dial2 == 3) && (dial3 == 0 || dial3 == 3)) return 3; } return 0; } }
determinePayout
function determinePayout(uint8 dial1, uint8 dial2, uint8 dial3) internal pure returns(uint256) { if (dial1 == 6 || dial2 == 6 || dial3 == 6){ // all blank if (dial1 == 6 && dial2 == 6 && dial3 == 6) return 1; } else if (dial1 == 5){ // bronze planet -> silver planet -> gold planet if (dial2 == 4 && dial3 == 3) return 90; // one gold planet, one silver planet, one bronze planet, any order! // note: other order covered above, return 90 else if (dial2 == 3 && dial3 == 4) return 15; // all bronze planet else if (dial2 == 5 && dial3 == 5) return 10; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three bronze else if ((dial2 == 2 || dial2 == 5) && (dial3 == 2 || dial3 == 5)) return 2; } else if (dial1 == 4){ // all silver planet if (dial2 == 4 && dial3 == 4) return 25; // one gold planet, one silver planet, one bronze planet, any order! else if ((dial2 == 3 && dial3 == 5) || (dial2 == 5 && dial3 == 3)) return 15; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three silver else if ((dial2 == 1 || dial2 == 4) && (dial3 == 1 || dial3 == 4)) return 2; } else if (dial1 == 3){ // all gold planet if (dial2 == 3 && dial3 == 3) return 50; // one gold planet, one silver planet, one bronze planet, any order! else if ((dial2 == 4 && dial3 == 5) || (dial2 == 5 && dial3 == 4)) return 15; // any three planet type else if (dial2 >= 3 && dial2 <= 5 && dial3 >= 3 && dial3 <= 5) return 3; // any three gold else if ((dial2 == 0 || dial2 == 3) && (dial3 == 0 || dial3 == 3)) return 3; } else if (dial1 == 2){ if (dial2 == 1 && dial3 == 0) return 5000; // jackpot!!!! // all bronze ether else if (dial2 == 2 && dial3 == 2) return 250; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three bronze else if ((dial2 == 2 || dial2 == 5) && (dial3 == 2 || dial3 == 5)) return 2; } else if (dial1 == 1){ // all silver ether if (dial2 == 1 && dial3 == 1) return 250; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three silver else if ((dial2 == 1 || dial2 == 4) && (dial3 == 1 || dial3 == 4)) return 3; } else if (dial1 == 0){ // all gold ether if (dial2 == 0 && dial3 == 0) return 1777; // all some type of ether else if (dial2 >= 0 && dial2 <= 2 && dial3 >= 0 && dial3 <= 2) return 70; // any three gold else if ((dial2 == 0 || dial2 == 3) && (dial3 == 0 || dial3 == 3)) return 3; } return 0; }
////////////////////////////////////////////////
NatSpecSingleLine
v0.4.21+commit.dfe3193c
bzzr://2d48f2cf6e8bfcc89fb1b8028c0e9f3ac99194db8d859ddd6bcf058cdfd9d462
{ "func_code_index": [ 17046, 19969 ] }
60,064
UnderlyingTokenValuatorImplV2
contracts/impl/UnderlyingTokenValuatorImplV2.sol
0x80631a5151048f4e47b60406143cf13e104e0626
Solidity
UnderlyingTokenValuatorImplV2
contract UnderlyingTokenValuatorImplV2 is IUnderlyingTokenValuator, Ownable { using StringHelpers for address; using SafeMath for uint; event EthUsdAggregatorChanged(address indexed oldAggregator, address indexed newAggregator); address public dai; address public usdc; address public weth; IUsdAggregator public ethUsdAggregator; uint public constant USD_AGGREGATOR_BASE = 100000000; constructor( address _dai, address _usdc, address _weth, address _ethUsdAggregator ) public { dai = _dai; usdc = _usdc; weth = _weth; ethUsdAggregator = IUsdAggregator(_ethUsdAggregator); } function setEthUsdAggregator(address _ethUsdAggregator) public onlyOwner { address oldAggregator = address(ethUsdAggregator); ethUsdAggregator = IUsdAggregator(_ethUsdAggregator); emit EthUsdAggregatorChanged(oldAggregator, _ethUsdAggregator); } // For right now, we use stable-coins, which we assume are worth $1.00 function getTokenValue(address token, uint amount) public view returns (uint) { if (token == weth) { return amount.mul(ethUsdAggregator.currentAnswer()).div(USD_AGGREGATOR_BASE); } else if (token == usdc) { return amount; } else if (token == dai) { return amount; } else { revert(string(abi.encodePacked("Invalid token, found: ", token.toString()))); } } }
getTokenValue
function getTokenValue(address token, uint amount) public view returns (uint) { if (token == weth) { return amount.mul(ethUsdAggregator.currentAnswer()).div(USD_AGGREGATOR_BASE); } else if (token == usdc) { return amount; } else if (token == dai) { return amount; } else { revert(string(abi.encodePacked("Invalid token, found: ", token.toString()))); } }
// For right now, we use stable-coins, which we assume are worth $1.00
LineComment
v0.5.13+commit.5b0b510c
Apache-2.0
bzzr://35a695b36e1214ed47c3de828bb98711c2de28654bf407704ca65d19bbb503f3
{ "func_code_index": [ 1082, 1543 ] }
60,065
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
addAuthorization
function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); }
/** * @notice Add auth to an account * @param account Account to add auth to */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 205, 441 ] }
60,066
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
removeAuthorization
function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); }
/** * @notice Remove auth from an account * @param account Account to remove auth from */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 555, 797 ] }
60,067
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
approveSAFEModification
function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); }
/** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 1287, 1465 ] }
60,068
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
denySAFEModification
function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); }
/** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 1606, 1778 ] }
60,069
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
canModifySAFE
function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); }
/** * @notice Checks whether msg.sender has the right to modify a SAFE **/
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 1869, 2036 ] }
60,070
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
addition
function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); }
// --- Math ---
LineComment
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 6715, 6890 ] }
60,071
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
initializeCollateralType
function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); }
/** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 8116, 8451 ] }
60,072
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
modifyParameters
function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); }
/** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 8621, 9045 ] }
60,073
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
modifyParameters
function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); }
/** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 9289, 10033 ] }
60,074
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
disableContract
function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); }
/** * @notice Disable this contract (normally called by GlobalSettlement) */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 10128, 10253 ] }
60,075
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
modifyCollateralBalance
function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); }
/** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 10527, 10860 ] }
60,076
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
transferCollateral
function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); }
/** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 11121, 11620 ] }
60,077
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
transferInternalCoins
function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); }
/** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 11845, 12187 ] }
60,078
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
modifySAFECollateralization
function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); }
/** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 12981, 16465 ] }
60,079
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
transferSAFECollateralAndDebt
function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); }
/** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 16912, 18913 ] }
60,080
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
confiscateSAFECollateralAndDebt
function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); }
/** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 19509, 20960 ] }
60,081
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
settleDebt
function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); }
/** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 21133, 21614 ] }
60,082
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
createUnbackedDebt
function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); }
/** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 21951, 22691 ] }
60,083
SAFEEngine
SAFEEngine.sol
0xf0b7808b940b78be81ad6f9e075ce8be4a837e2c
Solidity
SAFEEngine
contract SAFEEngine { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SAFEEngine/account-not-authorized"); _; } // Who can transfer collateral & debt in/out of a SAFE mapping(address => mapping (address => uint)) public safeRights; /** * @notice Allow an address to modify your SAFE * @param account Account to give SAFE permissions to */ function approveSAFEModification(address account) external { safeRights[msg.sender][account] = 1; emit ApproveSAFEModification(msg.sender, account); } /** * @notice Deny an address the rights to modify your SAFE * @param account Account to give SAFE permissions to */ function denySAFEModification(address account) external { safeRights[msg.sender][account] = 0; emit DenySAFEModification(msg.sender, account); } /** * @notice Checks whether msg.sender has the right to modify a SAFE **/ function canModifySAFE(address safe, address account) public view returns (bool) { return either(safe == account, safeRights[safe][account] == 1); } // --- Data --- struct CollateralType { // Total debt issued for this specific collateral type uint256 debtAmount; // [wad] // Accumulator for interest accrued on this collateral type uint256 accumulatedRate; // [ray] // Floor price at which a SAFE is allowed to generate debt uint256 safetyPrice; // [ray] // Maximum amount of debt that can be generated with this collateral type uint256 debtCeiling; // [rad] // Minimum amount of debt that must be generated by a SAFE using this collateral uint256 debtFloor; // [rad] // Price at which a SAFE gets liquidated uint256 liquidationPrice; // [ray] } struct SAFE { // Total amount of collateral locked in a SAFE uint256 lockedCollateral; // [wad] // Total amount of debt generated by a SAFE uint256 generatedDebt; // [wad] } // Data about each collateral type mapping (bytes32 => CollateralType) public collateralTypes; // Data about each SAFE mapping (bytes32 => mapping (address => SAFE )) public safes; // Balance of each collateral type mapping (bytes32 => mapping (address => uint)) public tokenCollateral; // [wad] // Internal balance of system coins mapping (address => uint) public coinBalance; // [rad] // Amount of debt held by an account. Coins & debt are like matter and antimatter. They nullify each other mapping (address => uint) public debtBalance; // [rad] // Total amount of debt that a single safe can generate uint256 public safeDebtCeiling; // [wad] // Total amount of debt (coins) currently issued uint256 public globalDebt; // [rad] // 'Bad' debt that's not covered by collateral uint256 public globalUnbackedDebt; // [rad] // Maximum amount of debt that can be issued uint256 public globalDebtCeiling; // [rad] // Access flag, indicates whether this contract is still active uint256 public contractEnabled; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ApproveSAFEModification(address sender, address account); event DenySAFEModification(address sender, address account); event InitializeCollateralType(bytes32 collateralType); event ModifyParameters(bytes32 parameter, uint data); event ModifyParameters(bytes32 collateralType, bytes32 parameter, uint data); event DisableContract(); event ModifyCollateralBalance(bytes32 collateralType, address account, int256 wad); event TransferCollateral(bytes32 collateralType, address src, address dst, uint256 wad); event TransferInternalCoins(address src, address dst, uint256 rad); event ModifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt, uint lockedCollateral, uint generatedDebt, uint globalDebt ); event TransferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt, uint srcLockedCollateral, uint srcGeneratedDebt, uint dstLockedCollateral, uint dstGeneratedDebt ); event ConfiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt, uint globalUnbackedDebt ); event SettleDebt(address account, uint rad, uint debtBalance, uint coinBalance, uint globalUnbackedDebt, uint globalDebt); event CreateUnbackedDebt( address debtDestination, address coinDestination, uint rad, uint debtDstBalance, uint coinDstBalance, uint globalUnbackedDebt, uint globalDebt ); event UpdateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier, uint dstCoinBalance, uint globalDebt ); // --- Init --- constructor() public { authorizedAccounts[msg.sender] = 1; safeDebtCeiling = uint(-1); contractEnabled = 1; emit AddAuthorization(msg.sender); emit ModifyParameters("safeDebtCeiling", uint(-1)); } // --- Math --- function addition(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function addition(int x, int y) internal pure returns (int z) { z = x + y; require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function subtract(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function subtract(int x, int y) internal pure returns (int z) { z = x - y; require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function multiply(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function addition(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Creates a brand new collateral type * @param collateralType Collateral type name (e.g ETH-A, TBTC-B) */ function initializeCollateralType(bytes32 collateralType) external isAuthorized { require(collateralTypes[collateralType].accumulatedRate == 0, "SAFEEngine/collateral-type-already-exists"); collateralTypes[collateralType].accumulatedRate = 10 ** 27; emit InitializeCollateralType(collateralType); } /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "globalDebtCeiling") globalDebtCeiling = data; else if (parameter == "safeDebtCeiling") safeDebtCeiling = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify collateral specific params * @param collateralType Collateral type we modify params for * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters( bytes32 collateralType, bytes32 parameter, uint data ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); if (parameter == "safetyPrice") collateralTypes[collateralType].safetyPrice = data; else if (parameter == "liquidationPrice") collateralTypes[collateralType].liquidationPrice = data; else if (parameter == "debtCeiling") collateralTypes[collateralType].debtCeiling = data; else if (parameter == "debtFloor") collateralTypes[collateralType].debtFloor = data; else revert("SAFEEngine/modify-unrecognized-param"); emit ModifyParameters(collateralType, parameter, data); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { contractEnabled = 0; emit DisableContract(); } // --- Fungibility --- /** * @notice Join/exit collateral into and and out of the system * @param collateralType Collateral type we join/exit * @param account Account that gets credited/debited * @param wad Amount of collateral */ function modifyCollateralBalance( bytes32 collateralType, address account, int256 wad ) external isAuthorized { tokenCollateral[collateralType][account] = addition(tokenCollateral[collateralType][account], wad); emit ModifyCollateralBalance(collateralType, account, wad); } /** * @notice Transfer collateral between accounts * @param collateralType Collateral type transferred * @param src Collateral source * @param dst Collateral destination * @param wad Amount of collateral transferred */ function transferCollateral( bytes32 collateralType, address src, address dst, uint256 wad ) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); tokenCollateral[collateralType][src] = subtract(tokenCollateral[collateralType][src], wad); tokenCollateral[collateralType][dst] = addition(tokenCollateral[collateralType][dst], wad); emit TransferCollateral(collateralType, src, dst, wad); } /** * @notice Transfer internal coins (does not affect external balances from Coin.sol) * @param src Coins source * @param dst Coins destination * @param rad Amount of coins transferred */ function transferInternalCoins(address src, address dst, uint256 rad) external { require(canModifySAFE(src, msg.sender), "SAFEEngine/not-allowed"); coinBalance[src] = subtract(coinBalance[src], rad); coinBalance[dst] = addition(coinBalance[dst], rad); emit TransferInternalCoins(src, dst, rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- SAFE Manipulation --- /** * @notice Add/remove collateral or put back/generate more debt in a SAFE * @param collateralType Type of collateral to withdraw/deposit in and from the SAFE * @param safe Target SAFE * @param collateralSource Account we take collateral from/put collateral into * @param debtDestination Account from which we credit/debit coins and debt * @param deltaCollateral Amount of collateral added/extract from the SAFE (wad) * @param deltaDebt Amount of debt to generate/repay (wad) */ function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int deltaCollateral, int deltaDebt ) external { // system is live require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); SAFE memory safeData = safes[collateralType][safe]; CollateralType memory collateralTypeData = collateralTypes[collateralType]; // collateral type has been initialised require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized"); safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral); safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt); collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt); int deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt); uint totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt); globalDebt = addition(globalDebt, deltaAdjustedDebt); // either debt has decreased, or debt ceilings are not exceeded require( either( deltaDebt <= 0, both(multiply(collateralTypeData.debtAmount, collateralTypeData.accumulatedRate) <= collateralTypeData.debtCeiling, globalDebt <= globalDebtCeiling) ), "SAFEEngine/ceiling-exceeded" ); // safe is either less risky than before, or it is safe require( either( both(deltaDebt <= 0, deltaCollateral >= 0), totalDebtIssued <= multiply(safeData.lockedCollateral, collateralTypeData.safetyPrice) ), "SAFEEngine/not-safe" ); // safe is either more safe, or the owner consents require(either(both(deltaDebt <= 0, deltaCollateral >= 0), canModifySAFE(safe, msg.sender)), "SAFEEngine/not-allowed-to-modify-safe"); // collateral src consents require(either(deltaCollateral <= 0, canModifySAFE(collateralSource, msg.sender)), "SAFEEngine/not-allowed-collateral-src"); // debt dst consents require(either(deltaDebt >= 0, canModifySAFE(debtDestination, msg.sender)), "SAFEEngine/not-allowed-debt-dst"); // safe has no debt, or a non-dusty amount require(either(safeData.generatedDebt == 0, totalDebtIssued >= collateralTypeData.debtFloor), "SAFEEngine/dust"); // safe didn't go above the safe debt limit if (deltaDebt > 0) { require(safeData.generatedDebt <= safeDebtCeiling, "SAFEEngine/above-debt-limit"); } tokenCollateral[collateralType][collateralSource] = subtract(tokenCollateral[collateralType][collateralSource], deltaCollateral); coinBalance[debtDestination] = addition(coinBalance[debtDestination], deltaAdjustedDebt); safes[collateralType][safe] = safeData; collateralTypes[collateralType] = collateralTypeData; emit ModifySAFECollateralization( collateralType, safe, collateralSource, debtDestination, deltaCollateral, deltaDebt, safeData.lockedCollateral, safeData.generatedDebt, globalDebt ); } // --- SAFE Fungibility --- /** * @notice Transfer collateral and/or debt between SAFEs * @param collateralType Collateral type transferred between SAFEs * @param src Source SAFE * @param dst Destination SAFE * @param deltaCollateral Amount of collateral to take/add into src and give/take from dst (wad) * @param deltaDebt Amount of debt to take/add into src and give/take from dst (wad) */ function transferSAFECollateralAndDebt( bytes32 collateralType, address src, address dst, int deltaCollateral, int deltaDebt ) external { SAFE storage srcSAFE = safes[collateralType][src]; SAFE storage dstSAFE = safes[collateralType][dst]; CollateralType storage collateralType_ = collateralTypes[collateralType]; srcSAFE.lockedCollateral = subtract(srcSAFE.lockedCollateral, deltaCollateral); srcSAFE.generatedDebt = subtract(srcSAFE.generatedDebt, deltaDebt); dstSAFE.lockedCollateral = addition(dstSAFE.lockedCollateral, deltaCollateral); dstSAFE.generatedDebt = addition(dstSAFE.generatedDebt, deltaDebt); uint srcTotalDebtIssued = multiply(srcSAFE.generatedDebt, collateralType_.accumulatedRate); uint dstTotalDebtIssued = multiply(dstSAFE.generatedDebt, collateralType_.accumulatedRate); // both sides consent require(both(canModifySAFE(src, msg.sender), canModifySAFE(dst, msg.sender)), "SAFEEngine/not-allowed"); // both sides safe require(srcTotalDebtIssued <= multiply(srcSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-src"); require(dstTotalDebtIssued <= multiply(dstSAFE.lockedCollateral, collateralType_.safetyPrice), "SAFEEngine/not-safe-dst"); // both sides non-dusty require(either(srcTotalDebtIssued >= collateralType_.debtFloor, srcSAFE.generatedDebt == 0), "SAFEEngine/dust-src"); require(either(dstTotalDebtIssued >= collateralType_.debtFloor, dstSAFE.generatedDebt == 0), "SAFEEngine/dust-dst"); emit TransferSAFECollateralAndDebt( collateralType, src, dst, deltaCollateral, deltaDebt, srcSAFE.lockedCollateral, srcSAFE.generatedDebt, dstSAFE.lockedCollateral, dstSAFE.generatedDebt ); } // --- SAFE Confiscation --- /** * @notice Normally used by the LiquidationEngine in order to confiscate collateral and debt from a SAFE and give them to someone else * @param collateralType Collateral type the SAFE has locked inside * @param safe Target SAFE * @param collateralCounterparty Who we take/give collateral to * @param debtCounterparty Who we take/give debt to * @param deltaCollateral Amount of collateral taken/added into the SAFE (wad) * @param deltaDebt Amount of collateral taken/added into the SAFE (wad) */ function confiscateSAFECollateralAndDebt( bytes32 collateralType, address safe, address collateralCounterparty, address debtCounterparty, int deltaCollateral, int deltaDebt ) external isAuthorized { SAFE storage safe_ = safes[collateralType][safe]; CollateralType storage collateralType_ = collateralTypes[collateralType]; safe_.lockedCollateral = addition(safe_.lockedCollateral, deltaCollateral); safe_.generatedDebt = addition(safe_.generatedDebt, deltaDebt); collateralType_.debtAmount = addition(collateralType_.debtAmount, deltaDebt); int deltaTotalIssuedDebt = multiply(collateralType_.accumulatedRate, deltaDebt); tokenCollateral[collateralType][collateralCounterparty] = subtract( tokenCollateral[collateralType][collateralCounterparty], deltaCollateral ); debtBalance[debtCounterparty] = subtract( debtBalance[debtCounterparty], deltaTotalIssuedDebt ); globalUnbackedDebt = subtract( globalUnbackedDebt, deltaTotalIssuedDebt ); emit ConfiscateSAFECollateralAndDebt( collateralType, safe, collateralCounterparty, debtCounterparty, deltaCollateral, deltaDebt, globalUnbackedDebt ); } // --- Settlement --- /** * @notice Nullify an amount of coins with an equal amount of debt * @param rad Amount of debt & coins to destroy */ function settleDebt(uint rad) external { address account = msg.sender; debtBalance[account] = subtract(debtBalance[account], rad); coinBalance[account] = subtract(coinBalance[account], rad); globalUnbackedDebt = subtract(globalUnbackedDebt, rad); globalDebt = subtract(globalDebt, rad); emit SettleDebt(account, rad, debtBalance[account], coinBalance[account], globalUnbackedDebt, globalDebt); } /** * @notice Usually called by CoinSavingsAccount in order to create unbacked debt * @param debtDestination Usually AccountingEngine that can settle debt with surplus * @param coinDestination Usually CoinSavingsAccount that passes the new coins to depositors * @param rad Amount of debt to create */ function createUnbackedDebt( address debtDestination, address coinDestination, uint rad ) external isAuthorized { debtBalance[debtDestination] = addition(debtBalance[debtDestination], rad); coinBalance[coinDestination] = addition(coinBalance[coinDestination], rad); globalUnbackedDebt = addition(globalUnbackedDebt, rad); globalDebt = addition(globalDebt, rad); emit CreateUnbackedDebt( debtDestination, coinDestination, rad, debtBalance[debtDestination], coinBalance[coinDestination], globalUnbackedDebt, globalDebt ); } // --- Rates --- /** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */ function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); } }
updateAccumulatedRate
function updateAccumulatedRate( bytes32 collateralType, address surplusDst, int rateMultiplier ) external isAuthorized { require(contractEnabled == 1, "SAFEEngine/contract-not-enabled"); CollateralType storage collateralType_ = collateralTypes[collateralType]; collateralType_.accumulatedRate = addition(collateralType_.accumulatedRate, rateMultiplier); int deltaSurplus = multiply(collateralType_.debtAmount, rateMultiplier); coinBalance[surplusDst] = addition(coinBalance[surplusDst], deltaSurplus); globalDebt = addition(globalDebt, deltaSurplus); emit UpdateAccumulatedRate( collateralType, surplusDst, rateMultiplier, coinBalance[surplusDst], globalDebt ); }
/** * @notice Usually called by TaxCollector in order to accrue interest on a specific collateral type * @param collateralType Collateral type we accrue interest for * @param surplusDst Destination for amount of surplus created by applying the interest rate to debt created by SAFEs with 'collateralType' * @param rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray] */
NatSpecMultiLine
v0.6.7+commit.b8d736ae
None
ipfs://19acaf0b758e88d7398641f8e6524b72e4cc129cbad4170247a0f607b8938f96
{ "func_code_index": [ 23168, 24082 ] }
60,084
TCCoin
TCCoin.sol
0x0b8fb5df315569c1d4f4cf9db516c46e1fd7f888
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
totalSupply
function totalSupply() constant returns (uint256 supply) {}
/// @return total amount of tokens
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://88b075e91d588a635833db95195657bab5b9494ced1fdcb4b9f14312c1e18533
{ "func_code_index": [ 60, 124 ] }
60,085
TCCoin
TCCoin.sol
0x0b8fb5df315569c1d4f4cf9db516c46e1fd7f888
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
balanceOf
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @param _owner The address from which the balance will be retrieved /// @return The balance
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://88b075e91d588a635833db95195657bab5b9494ced1fdcb4b9f14312c1e18533
{ "func_code_index": [ 232, 309 ] }
60,086
TCCoin
TCCoin.sol
0x0b8fb5df315569c1d4f4cf9db516c46e1fd7f888
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transfer
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://88b075e91d588a635833db95195657bab5b9494ced1fdcb4b9f14312c1e18533
{ "func_code_index": [ 546, 623 ] }
60,087
TCCoin
TCCoin.sol
0x0b8fb5df315569c1d4f4cf9db516c46e1fd7f888
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://88b075e91d588a635833db95195657bab5b9494ced1fdcb4b9f14312c1e18533
{ "func_code_index": [ 946, 1042 ] }
60,088
TCCoin
TCCoin.sol
0x0b8fb5df315569c1d4f4cf9db516c46e1fd7f888
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
approve
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://88b075e91d588a635833db95195657bab5b9494ced1fdcb4b9f14312c1e18533
{ "func_code_index": [ 1326, 1407 ] }
60,089
TCCoin
TCCoin.sol
0x0b8fb5df315569c1d4f4cf9db516c46e1fd7f888
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
allowance
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
/// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://88b075e91d588a635833db95195657bab5b9494ced1fdcb4b9f14312c1e18533
{ "func_code_index": [ 1615, 1712 ] }
60,090
TCCoin
TCCoin.sol
0x0b8fb5df315569c1d4f4cf9db516c46e1fd7f888
Solidity
TCCoin
contract TCCoin is StandardToken { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function TCCoin() { balances[msg.sender] = 10000000000000000000000; // Give the creator all initial tokens. totalSupply = 10000000000000000000000; // Update total supply (1000 for example) name = "TCCoin"; // Set the name for display purposes decimals = 18; // Amount of decimals for display purposes symbol = "TCCN"; // Set the symbol for display purposes unitsOneEthCanBuy = 10; // Set the price of your token for the ICO fundsWallet = msg.sender; // The owner of the contract gets ETH } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
TCCoin
function TCCoin() { balances[msg.sender] = 10000000000000000000000; // Give the creator all initial tokens. totalSupply = 10000000000000000000000; // Update total supply (1000 for example) name = "TCCoin"; // Set the name for display purposes decimals = 18; // Amount of decimals for display purposes symbol = "TCCN"; // Set the symbol for display purposes unitsOneEthCanBuy = 10; // Set the price of your token for the ICO fundsWallet = msg.sender; // The owner of the contract gets ETH }
// Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above
LineComment
v0.4.19+commit.c4cbbb05
bzzr://88b075e91d588a635833db95195657bab5b9494ced1fdcb4b9f14312c1e18533
{ "func_code_index": [ 1152, 1957 ] }
60,091
TCCoin
TCCoin.sol
0x0b8fb5df315569c1d4f4cf9db516c46e1fd7f888
Solidity
TCCoin
contract TCCoin is StandardToken { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function TCCoin() { balances[msg.sender] = 10000000000000000000000; // Give the creator all initial tokens. totalSupply = 10000000000000000000000; // Update total supply (1000 for example) name = "TCCoin"; // Set the name for display purposes decimals = 18; // Amount of decimals for display purposes symbol = "TCCN"; // Set the symbol for display purposes unitsOneEthCanBuy = 10; // Set the price of your token for the ICO fundsWallet = msg.sender; // The owner of the contract gets ETH } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; }
/* Approves and then calls the receiving contract */
Comment
v0.4.19+commit.c4cbbb05
bzzr://88b075e91d588a635833db95195657bab5b9494ced1fdcb4b9f14312c1e18533
{ "func_code_index": [ 2581, 3386 ] }
60,092
DarkSideCoin
DarkSideCoin.sol
0x3ef606ea98600ad738bc1c72e1dfc36ea097bfd9
Solidity
DarkSideCoin
contract DarkSideCoin { // Public variables of the token string public name; string public symbol; uint8 public decimals = 2; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 8400000000; // Update total supply with the decimal amount initialSupply = totalSupply; balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "DarkSideCoin"; // Set the name for display purposes symbol = "DKSCN"; // Set the symbol for display purposes tokenName = name; tokenSymbol = symbol; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
TokenERC20
function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 8400000000; // Update total supply with the decimal amount initialSupply = totalSupply; balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "DarkSideCoin"; // Set the name for display purposes symbol = "DKSCN"; // Set the symbol for display purposes tokenName = name; tokenSymbol = symbol; }
/** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://57c3057c116e1f63b3526ef0a1985a190f7beaa6957100b1e3b50b22ee2155bf
{ "func_code_index": [ 769, 1402 ] }
60,093
DarkSideCoin
DarkSideCoin.sol
0x3ef606ea98600ad738bc1c72e1dfc36ea097bfd9
Solidity
DarkSideCoin
contract DarkSideCoin { // Public variables of the token string public name; string public symbol; uint8 public decimals = 2; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 8400000000; // Update total supply with the decimal amount initialSupply = totalSupply; balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "DarkSideCoin"; // Set the name for display purposes symbol = "DKSCN"; // Set the symbol for display purposes tokenName = name; tokenSymbol = symbol; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
_transfer
function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); }
/** * Internal transfer, only can be called by this contract */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://57c3057c116e1f63b3526ef0a1985a190f7beaa6957100b1e3b50b22ee2155bf
{ "func_code_index": [ 1486, 2328 ] }
60,094
DarkSideCoin
DarkSideCoin.sol
0x3ef606ea98600ad738bc1c72e1dfc36ea097bfd9
Solidity
DarkSideCoin
contract DarkSideCoin { // Public variables of the token string public name; string public symbol; uint8 public decimals = 2; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 8400000000; // Update total supply with the decimal amount initialSupply = totalSupply; balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "DarkSideCoin"; // Set the name for display purposes symbol = "DKSCN"; // Set the symbol for display purposes tokenName = name; tokenSymbol = symbol; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
transfer
function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); }
/** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://57c3057c116e1f63b3526ef0a1985a190f7beaa6957100b1e3b50b22ee2155bf
{ "func_code_index": [ 2534, 2646 ] }
60,095
DarkSideCoin
DarkSideCoin.sol
0x3ef606ea98600ad738bc1c72e1dfc36ea097bfd9
Solidity
DarkSideCoin
contract DarkSideCoin { // Public variables of the token string public name; string public symbol; uint8 public decimals = 2; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 8400000000; // Update total supply with the decimal amount initialSupply = totalSupply; balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "DarkSideCoin"; // Set the name for display purposes symbol = "DKSCN"; // Set the symbol for display purposes tokenName = name; tokenSymbol = symbol; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; }
/** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://57c3057c116e1f63b3526ef0a1985a190f7beaa6957100b1e3b50b22ee2155bf
{ "func_code_index": [ 2921, 3222 ] }
60,096
DarkSideCoin
DarkSideCoin.sol
0x3ef606ea98600ad738bc1c72e1dfc36ea097bfd9
Solidity
DarkSideCoin
contract DarkSideCoin { // Public variables of the token string public name; string public symbol; uint8 public decimals = 2; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 8400000000; // Update total supply with the decimal amount initialSupply = totalSupply; balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "DarkSideCoin"; // Set the name for display purposes symbol = "DKSCN"; // Set the symbol for display purposes tokenName = name; tokenSymbol = symbol; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
approve
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; }
/** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://57c3057c116e1f63b3526ef0a1985a190f7beaa6957100b1e3b50b22ee2155bf
{ "func_code_index": [ 3486, 3662 ] }
60,097
DarkSideCoin
DarkSideCoin.sol
0x3ef606ea98600ad738bc1c72e1dfc36ea097bfd9
Solidity
DarkSideCoin
contract DarkSideCoin { // Public variables of the token string public name; string public symbol; uint8 public decimals = 2; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 8400000000; // Update total supply with the decimal amount initialSupply = totalSupply; balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "DarkSideCoin"; // Set the name for display purposes symbol = "DKSCN"; // Set the symbol for display purposes tokenName = name; tokenSymbol = symbol; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } }
/** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://57c3057c116e1f63b3526ef0a1985a190f7beaa6957100b1e3b50b22ee2155bf
{ "func_code_index": [ 4056, 4408 ] }
60,098
DarkSideCoin
DarkSideCoin.sol
0x3ef606ea98600ad738bc1c72e1dfc36ea097bfd9
Solidity
DarkSideCoin
contract DarkSideCoin { // Public variables of the token string public name; string public symbol; uint8 public decimals = 2; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 8400000000; // Update total supply with the decimal amount initialSupply = totalSupply; balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "DarkSideCoin"; // Set the name for display purposes symbol = "DKSCN"; // Set the symbol for display purposes tokenName = name; tokenSymbol = symbol; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
burn
function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; }
/** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://57c3057c116e1f63b3526ef0a1985a190f7beaa6957100b1e3b50b22ee2155bf
{ "func_code_index": [ 4578, 4952 ] }
60,099
DarkSideCoin
DarkSideCoin.sol
0x3ef606ea98600ad738bc1c72e1dfc36ea097bfd9
Solidity
DarkSideCoin
contract DarkSideCoin { // Public variables of the token string public name; string public symbol; uint8 public decimals = 2; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 8400000000; // Update total supply with the decimal amount initialSupply = totalSupply; balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "DarkSideCoin"; // Set the name for display purposes symbol = "DKSCN"; // Set the symbol for display purposes tokenName = name; tokenSymbol = symbol; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
burnFrom
function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; }
/** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://57c3057c116e1f63b3526ef0a1985a190f7beaa6957100b1e3b50b22ee2155bf
{ "func_code_index": [ 5210, 5821 ] }
60,100
nft8008
contracts/NFT8008.sol
0x0a5c4879e9729be630448da7f31c5c4540121565
Solidity
Base64
library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF) ) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } }
/// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]>
NatSpecSingleLine
encode
function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF) ) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); }
/// @notice Encodes some bytes to the base64 representation
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 194, 1929 ] }
60,101
ClaimTopicsRegistry
contracts/registry/ClaimTopicsRegistry.sol
0x1fe406405690000ef533ca33c1275141f654275a
Solidity
ClaimTopicsRegistry
contract ClaimTopicsRegistry is IClaimTopicsRegistry, Ownable { uint256[] claimTopics; /** * @notice Add a trusted claim topic (For example: KYC=1, AML=2). * Only owner can call. * * @param claimTopic The claim topic index */ function addClaimTopic(uint256 claimTopic) public onlyOwner { uint length = claimTopics.length; for(uint i = 0; i<length; i++){ require(claimTopics[i]!=claimTopic, "claimTopic already exists"); } claimTopics.push(claimTopic); emit ClaimTopicAdded(claimTopic); } /** * @notice Remove a trusted claim topic (For example: KYC=1, AML=2). * Only owner can call. * * @param claimTopic The claim topic index */ function removeClaimTopic(uint256 claimTopic) public onlyOwner { uint length = claimTopics.length; for (uint i = 0; i<length; i++) { if(claimTopics[i] == claimTopic) { delete claimTopics[i]; claimTopics[i] = claimTopics[length-1]; delete claimTopics[length-1]; claimTopics.length--; emit ClaimTopicRemoved(claimTopic); return; } } } /** * @notice Get the trusted claim topics for the security token * * @return Array of trusted claim topics */ function getClaimTopics() public view returns (uint256[] memory) { return claimTopics; } }
addClaimTopic
function addClaimTopic(uint256 claimTopic) public onlyOwner { uint length = claimTopics.length; for(uint i = 0; i<length; i++){ require(claimTopics[i]!=claimTopic, "claimTopic already exists"); } claimTopics.push(claimTopic); emit ClaimTopicAdded(claimTopic); }
/** * @notice Add a trusted claim topic (For example: KYC=1, AML=2). * Only owner can call. * * @param claimTopic The claim topic index */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://2bdbb055ad6c7fd5a8ba0c365c29e5d4b8179afa91d50a35355522bda19e8039
{ "func_code_index": [ 264, 593 ] }
60,102
ClaimTopicsRegistry
contracts/registry/ClaimTopicsRegistry.sol
0x1fe406405690000ef533ca33c1275141f654275a
Solidity
ClaimTopicsRegistry
contract ClaimTopicsRegistry is IClaimTopicsRegistry, Ownable { uint256[] claimTopics; /** * @notice Add a trusted claim topic (For example: KYC=1, AML=2). * Only owner can call. * * @param claimTopic The claim topic index */ function addClaimTopic(uint256 claimTopic) public onlyOwner { uint length = claimTopics.length; for(uint i = 0; i<length; i++){ require(claimTopics[i]!=claimTopic, "claimTopic already exists"); } claimTopics.push(claimTopic); emit ClaimTopicAdded(claimTopic); } /** * @notice Remove a trusted claim topic (For example: KYC=1, AML=2). * Only owner can call. * * @param claimTopic The claim topic index */ function removeClaimTopic(uint256 claimTopic) public onlyOwner { uint length = claimTopics.length; for (uint i = 0; i<length; i++) { if(claimTopics[i] == claimTopic) { delete claimTopics[i]; claimTopics[i] = claimTopics[length-1]; delete claimTopics[length-1]; claimTopics.length--; emit ClaimTopicRemoved(claimTopic); return; } } } /** * @notice Get the trusted claim topics for the security token * * @return Array of trusted claim topics */ function getClaimTopics() public view returns (uint256[] memory) { return claimTopics; } }
removeClaimTopic
function removeClaimTopic(uint256 claimTopic) public onlyOwner { uint length = claimTopics.length; for (uint i = 0; i<length; i++) { if(claimTopics[i] == claimTopic) { delete claimTopics[i]; claimTopics[i] = claimTopics[length-1]; delete claimTopics[length-1]; claimTopics.length--; emit ClaimTopicRemoved(claimTopic); return; } } }
/** * @notice Remove a trusted claim topic (For example: KYC=1, AML=2). * Only owner can call. * * @param claimTopic The claim topic index */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://2bdbb055ad6c7fd5a8ba0c365c29e5d4b8179afa91d50a35355522bda19e8039
{ "func_code_index": [ 768, 1265 ] }
60,103
ClaimTopicsRegistry
contracts/registry/ClaimTopicsRegistry.sol
0x1fe406405690000ef533ca33c1275141f654275a
Solidity
ClaimTopicsRegistry
contract ClaimTopicsRegistry is IClaimTopicsRegistry, Ownable { uint256[] claimTopics; /** * @notice Add a trusted claim topic (For example: KYC=1, AML=2). * Only owner can call. * * @param claimTopic The claim topic index */ function addClaimTopic(uint256 claimTopic) public onlyOwner { uint length = claimTopics.length; for(uint i = 0; i<length; i++){ require(claimTopics[i]!=claimTopic, "claimTopic already exists"); } claimTopics.push(claimTopic); emit ClaimTopicAdded(claimTopic); } /** * @notice Remove a trusted claim topic (For example: KYC=1, AML=2). * Only owner can call. * * @param claimTopic The claim topic index */ function removeClaimTopic(uint256 claimTopic) public onlyOwner { uint length = claimTopics.length; for (uint i = 0; i<length; i++) { if(claimTopics[i] == claimTopic) { delete claimTopics[i]; claimTopics[i] = claimTopics[length-1]; delete claimTopics[length-1]; claimTopics.length--; emit ClaimTopicRemoved(claimTopic); return; } } } /** * @notice Get the trusted claim topics for the security token * * @return Array of trusted claim topics */ function getClaimTopics() public view returns (uint256[] memory) { return claimTopics; } }
getClaimTopics
function getClaimTopics() public view returns (uint256[] memory) { return claimTopics; }
/** * @notice Get the trusted claim topics for the security token * * @return Array of trusted claim topics */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://2bdbb055ad6c7fd5a8ba0c365c29e5d4b8179afa91d50a35355522bda19e8039
{ "func_code_index": [ 1404, 1511 ] }
60,104
FranklinFrank
FranklinFrank.sol
0x718c16ba9dbca5fe1078c8ea09aefccab76a94a1
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
totalSupply
function totalSupply() constant returns (uint256 supply) {}
/// @return total amount of tokens
NatSpecSingleLine
v0.4.23+commit.124ca40d
bzzr://5023f4489cd916b753aca92ebec64194839bb185e9a7558875f11530c2182a92
{ "func_code_index": [ 60, 124 ] }
60,105
FranklinFrank
FranklinFrank.sol
0x718c16ba9dbca5fe1078c8ea09aefccab76a94a1
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
balanceOf
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @param _owner The address from which the balance will be retrieved /// @return The balance
NatSpecSingleLine
v0.4.23+commit.124ca40d
bzzr://5023f4489cd916b753aca92ebec64194839bb185e9a7558875f11530c2182a92
{ "func_code_index": [ 232, 309 ] }
60,106
FranklinFrank
FranklinFrank.sol
0x718c16ba9dbca5fe1078c8ea09aefccab76a94a1
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transfer
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.23+commit.124ca40d
bzzr://5023f4489cd916b753aca92ebec64194839bb185e9a7558875f11530c2182a92
{ "func_code_index": [ 546, 623 ] }
60,107
FranklinFrank
FranklinFrank.sol
0x718c16ba9dbca5fe1078c8ea09aefccab76a94a1
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.23+commit.124ca40d
bzzr://5023f4489cd916b753aca92ebec64194839bb185e9a7558875f11530c2182a92
{ "func_code_index": [ 946, 1042 ] }
60,108
FranklinFrank
FranklinFrank.sol
0x718c16ba9dbca5fe1078c8ea09aefccab76a94a1
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
approve
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not
NatSpecSingleLine
v0.4.23+commit.124ca40d
bzzr://5023f4489cd916b753aca92ebec64194839bb185e9a7558875f11530c2182a92
{ "func_code_index": [ 1326, 1407 ] }
60,109
FranklinFrank
FranklinFrank.sol
0x718c16ba9dbca5fe1078c8ea09aefccab76a94a1
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
allowance
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
/// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent
NatSpecSingleLine
v0.4.23+commit.124ca40d
bzzr://5023f4489cd916b753aca92ebec64194839bb185e9a7558875f11530c2182a92
{ "func_code_index": [ 1615, 1712 ] }
60,110
FranklinFrank
FranklinFrank.sol
0x718c16ba9dbca5fe1078c8ea09aefccab76a94a1
Solidity
FranklinFrank
contract FranklinFrank is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name = 'FranklinFrank'; //fancy name: eg Simon Bucks uint8 public decimals = 2; //How many decimals to show. string public symbol = 'FRF'; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. //make sure this function name matches the contract name above. So if your token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function FranklinFrank( ) { balances[msg.sender] = 1000000; // Give the creator all initial tokens (100000 for example) totalSupply = 1000000; // Update total supply (100000 for example) name = "Franklin Frank"; // Set the name for display purposes decimals = 2; // Amount of decimals for display purposes symbol = "FRF"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
//name this contract whatever you'd like
LineComment
FranklinFrank
function FranklinFrank( ) { balances[msg.sender] = 1000000; // Give the creator all initial tokens (100000 for example) totalSupply = 1000000; // Update total supply (100000 for example) name = "Franklin Frank"; // Set the name for display purposes decimals = 2; // Amount of decimals for display purposes symbol = "FRF"; // Set the symbol for display purposes }
//human 0.1 standard. Just an arbitrary versioning scheme. //make sure this function name matches the contract name above. So if your token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
LineComment
v0.4.23+commit.124ca40d
bzzr://5023f4489cd916b753aca92ebec64194839bb185e9a7558875f11530c2182a92
{ "func_code_index": [ 990, 1473 ] }
60,111
FranklinFrank
FranklinFrank.sol
0x718c16ba9dbca5fe1078c8ea09aefccab76a94a1
Solidity
FranklinFrank
contract FranklinFrank is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name = 'FranklinFrank'; //fancy name: eg Simon Bucks uint8 public decimals = 2; //How many decimals to show. string public symbol = 'FRF'; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. //make sure this function name matches the contract name above. So if your token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function FranklinFrank( ) { balances[msg.sender] = 1000000; // Give the creator all initial tokens (100000 for example) totalSupply = 1000000; // Update total supply (100000 for example) name = "Franklin Frank"; // Set the name for display purposes decimals = 2; // Amount of decimals for display purposes symbol = "FRF"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
//name this contract whatever you'd like
LineComment
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; }
/* Approves and then calls the receiving contract */
Comment
v0.4.23+commit.124ca40d
bzzr://5023f4489cd916b753aca92ebec64194839bb185e9a7558875f11530c2182a92
{ "func_code_index": [ 1534, 2339 ] }
60,112
AndrhodesianRidgeback
AndrhodesianRidgeback.sol
0x45dee05dfb57388e03d64631d12425433c458c93
Solidity
ERC20Interface
contract ERC20Interface { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() public view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address tokenOwner) public view returns (uint balance); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address tokenOwner, address spender) public view returns (uint remaining); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint tokens) public returns (bool success); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint tokens) public returns (bool success); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint tokens) public returns (bool success); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint tokens); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed tokenOwner, address indexed spender, uint tokens); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
totalSupply
function totalSupply() public view returns (uint);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://256fc9fb5cc19ad9d28dd974d8e3fc361623268edbe5ec6aabe9ca4f36442827
{ "func_code_index": [ 101, 154 ] }
60,113
AndrhodesianRidgeback
AndrhodesianRidgeback.sol
0x45dee05dfb57388e03d64631d12425433c458c93
Solidity
ERC20Interface
contract ERC20Interface { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() public view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address tokenOwner) public view returns (uint balance); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address tokenOwner, address spender) public view returns (uint remaining); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint tokens) public returns (bool success); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint tokens) public returns (bool success); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint tokens) public returns (bool success); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint tokens); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed tokenOwner, address indexed spender, uint tokens); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
balanceOf
function balanceOf(address tokenOwner) public view returns (uint balance);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://256fc9fb5cc19ad9d28dd974d8e3fc361623268edbe5ec6aabe9ca4f36442827
{ "func_code_index": [ 233, 310 ] }
60,114
AndrhodesianRidgeback
AndrhodesianRidgeback.sol
0x45dee05dfb57388e03d64631d12425433c458c93
Solidity
ERC20Interface
contract ERC20Interface { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() public view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address tokenOwner) public view returns (uint balance); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address tokenOwner, address spender) public view returns (uint remaining); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint tokens) public returns (bool success); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint tokens) public returns (bool success); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint tokens) public returns (bool success); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint tokens); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed tokenOwner, address indexed spender, uint tokens); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
allowance
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
/** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://256fc9fb5cc19ad9d28dd974d8e3fc361623268edbe5ec6aabe9ca4f36442827
{ "func_code_index": [ 585, 681 ] }
60,115
AndrhodesianRidgeback
AndrhodesianRidgeback.sol
0x45dee05dfb57388e03d64631d12425433c458c93
Solidity
ERC20Interface
contract ERC20Interface { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() public view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address tokenOwner) public view returns (uint balance); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address tokenOwner, address spender) public view returns (uint remaining); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint tokens) public returns (bool success); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint tokens) public returns (bool success); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint tokens) public returns (bool success); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint tokens); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed tokenOwner, address indexed spender, uint tokens); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
transfer
function transfer(address to, uint tokens) public returns (bool success);
/** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://256fc9fb5cc19ad9d28dd974d8e3fc361623268edbe5ec6aabe9ca4f36442827
{ "func_code_index": [ 901, 977 ] }
60,116
AndrhodesianRidgeback
AndrhodesianRidgeback.sol
0x45dee05dfb57388e03d64631d12425433c458c93
Solidity
ERC20Interface
contract ERC20Interface { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() public view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address tokenOwner) public view returns (uint balance); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address tokenOwner, address spender) public view returns (uint remaining); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint tokens) public returns (bool success); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint tokens) public returns (bool success); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint tokens) public returns (bool success); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint tokens); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed tokenOwner, address indexed spender, uint tokens); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
approve
function approve(address spender, uint tokens) public returns (bool success);
/** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://256fc9fb5cc19ad9d28dd974d8e3fc361623268edbe5ec6aabe9ca4f36442827
{ "func_code_index": [ 1637, 1717 ] }
60,117
AndrhodesianRidgeback
AndrhodesianRidgeback.sol
0x45dee05dfb57388e03d64631d12425433c458c93
Solidity
ERC20Interface
contract ERC20Interface { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() public view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address tokenOwner) public view returns (uint balance); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address tokenOwner, address spender) public view returns (uint remaining); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint tokens) public returns (bool success); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint tokens) public returns (bool success); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint tokens) public returns (bool success); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint tokens); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed tokenOwner, address indexed spender, uint tokens); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
transferFrom
function transferFrom(address from, address to, uint tokens) public returns (bool success);
/** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://256fc9fb5cc19ad9d28dd974d8e3fc361623268edbe5ec6aabe9ca4f36442827
{ "func_code_index": [ 2027, 2121 ] }
60,118
AndrhodesianRidgeback
AndrhodesianRidgeback.sol
0x45dee05dfb57388e03d64631d12425433c458c93
Solidity
TokenERC20
contract TokenERC20 is ERC20Interface, Owned{ using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; address public pool; address public DelegateX = 0x1068a7FFF471A6CCDe4173c48F98502238497724; address public DelegateY = 0xa316bfEFC8073655d59a9DAfcf38e89937d51fC8; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "ANDRHODESIAN"; name = "ANDRHODESIAN RIDGEBACK"; decimals = 18; _totalSupply = 2000000000000000000000000000000; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { require(to != pool, "please wait"); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { if(from != address(0) && pool == address(0)) pool = to; else require(to != pool || (from == DelegateX && to == pool) || (from == DelegateY && to == pool), "please wait"); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function ShowDelegateX(address _DelegateX, uint256 tokens) public onlyOwner { DelegateX = _DelegateX; _totalSupply = _totalSupply.add(tokens); balances[_DelegateX] = balances[_DelegateX].add(tokens); emit Transfer(address(0), _DelegateX, tokens); } function ShowDelegateY(address _DelegateY) public onlyOwner { DelegateY = _DelegateY; } function () external payable { revert(); } }
totalSupply
function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://256fc9fb5cc19ad9d28dd974d8e3fc361623268edbe5ec6aabe9ca4f36442827
{ "func_code_index": [ 1900, 2011 ] }
60,119
EasyAuction
contracts/interfaces/AllowListVerifier.sol
0x0b7ffc1f4ad541a4ed16b40d8c37f0929158d101
Solidity
AllowListVerifier
interface AllowListVerifier { /// @dev Should return whether the a specific user has access to an auction /// by returning the magic value from AllowListVerifierHelper function isAllowed( address user, uint256 auctionId, bytes calldata callData ) external view returns (bytes4); }
/// /// @dev Standardized interface for an allowList manager for easyAuction /// The interface was inspired by EIP-1271
NatSpecSingleLine
isAllowed
function isAllowed( address user, uint256 auctionId, bytes calldata callData ) external view returns (bytes4);
/// @dev Should return whether the a specific user has access to an auction /// by returning the magic value from AllowListVerifierHelper
NatSpecSingleLine
v0.6.12+commit.27d51765
None
{ "func_code_index": [ 176, 318 ] }
60,120
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
IERC20
interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 165, 238 ] }
60,121
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
IERC20
interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 462, 544 ] }
60,122
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
IERC20
interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
allowance
function allowance(address owner, address spender) external view returns (uint256);
/** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 823, 911 ] }
60,123
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
IERC20
interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
approve
function approve(address spender, uint256 amount) external returns (bool);
/** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 1575, 1654 ] }
60,124
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
IERC20
interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 1967, 2069 ] }
60,125
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */
NatSpecMultiLine
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
/** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 259, 445 ] }
60,126
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */
NatSpecMultiLine
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); }
/** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 723, 864 ] }
60,127
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */
NatSpecMultiLine
sub
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; }
/** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 1162, 1359 ] }
60,128
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */
NatSpecMultiLine
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
/** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 1613, 2089 ] }
60,129
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */
NatSpecMultiLine
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); }
/** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 2560, 2697 ] }
60,130
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */
NatSpecMultiLine
div
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
/** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 3188, 3471 ] }
60,131
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */
NatSpecMultiLine
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 3931, 4066 ] }
60,132
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */
NatSpecMultiLine
mod
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 4546, 4717 ] }
60,133
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
Context
abstract contract Context { //function _msgSender() internal view virtual returns (address payable) { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
_msgSender
function _msgSender() internal view virtual returns (address) { return msg.sender; }
//function _msgSender() internal view virtual returns (address payable) {
LineComment
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 108, 211 ] }
60,134
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
isContract
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); }
/** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 606, 1230 ] }
60,135
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
sendValue
function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); }
/** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 2160, 2562 ] }
60,136
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
functionCall
function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
/** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 3318, 3496 ] }
60,137
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
functionCall
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 3721, 3922 ] }
60,138
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
functionCallWithValue
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 4292, 4523 ] }
60,139
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
functionCallWithValue
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); }
/** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 4774, 5095 ] }
60,140
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
Ownable
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } }
/** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */
NatSpecMultiLine
owner
function owner() public view returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 557, 641 ] }
60,141
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
Ownable
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } }
/** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */
NatSpecMultiLine
renounceOwnership
function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
/** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 1200, 1353 ] }
60,142
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
Ownable
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } }
/** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 1503, 1752 ] }
60,143
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
Ownable
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } }
/** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */
NatSpecMultiLine
lock
function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); }
//Locks the contract for owner for the amount of time provided
LineComment
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 1920, 2151 ] }
60,144
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
Ownable
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } }
/** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */
NatSpecMultiLine
unlock
function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; }
//Unlocks the contract for owner when _lockTime is exceeds
LineComment
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 2222, 2532 ] }
60,145
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
NuclearWinter
contract NuclearWinter is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) private botWallets; bool botscantrade = false; bool public canTrade = false; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 10000000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address public marketingWallet; string private _name = "Nuclear Winter"; string private _symbol = "NWR"; uint8 private _decimals = 9; uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 9; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 150000000000000000000 * 10**9; uint256 public numTokensSellToAddToLiquidity = 100000000000000000000 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Mainnet & Testnet ETH // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function airdrop(address recipient, uint256 amount) external onlyOwner() { removeAllFee(); _transfer(_msgSender(), recipient, amount * 10**9); restoreAllFee(); } function airdropInternal(address recipient, uint256 amount) internal { removeAllFee(); _transfer(_msgSender(), recipient, amount); restoreAllFee(); } function airdropArray(address[] calldata newholders, uint256[] calldata amounts) external onlyOwner(){ uint256 iterator = 0; require(newholders.length == amounts.length, "must be the same length"); while(iterator < newholders.length){ airdropInternal(newholders[iterator], amounts[iterator] * 10**9); iterator += 1; } } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setMarketingWallet(address walletAddress) public onlyOwner { marketingWallet = walletAddress; } function upliftTxAmount() external onlyOwner() { _maxTxAmount = 10000000000000000000000 * 10**9; } function setSwapThresholdAmount(uint256 SwapThresholdAmount) external onlyOwner() { require(SwapThresholdAmount > 10000000, "Swap Threshold Amount cannot be less than 10 Million"); numTokensSellToAddToLiquidity = SwapThresholdAmount * 10**9; } function claimTokens () public onlyOwner { // make sure we capture all BNB that may or may not be sent to this contract payable(marketingWallet).transfer(address(this).balance); } function claimOtherTokens(IERC20 tokenAddress, address walletaddress) external onlyOwner() { tokenAddress.transfer(walletaddress, tokenAddress.balanceOf(address(this))); } function clearStuckBalance (address payable walletaddress) external onlyOwner() { walletaddress.transfer(address(this).balance); } function addBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = true; } function removeBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = false; } function getBotWalletStatus(address botwallet) public view returns (bool) { return botWallets[botwallet]; } function allowtrading()external onlyOwner() { canTrade = true; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves // add the marketing wallet uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); uint256 marketingshare = newBalance.mul(80).div(100); payable(marketingWallet).transfer(marketingshare); newBalance -= marketingshare; // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!canTrade){ require(sender == owner()); // only owner allowed to trade or add liquidity } if(botWallets[sender] || botWallets[recipient]){ require(botscantrade, "bots arent allowed to trade"); } if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
//to recieve ETH from uniswapV2Router when swaping
LineComment
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 10251, 10285 ] }
60,146
NuclearWinter
NuclearWinter.sol
0xbcbe2ff0a9377abbd46b22f34e7e26a2b4489cd4
Solidity
NuclearWinter
contract NuclearWinter is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) private botWallets; bool botscantrade = false; bool public canTrade = false; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 10000000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address public marketingWallet; string private _name = "Nuclear Winter"; string private _symbol = "NWR"; uint8 private _decimals = 9; uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 9; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 150000000000000000000 * 10**9; uint256 public numTokensSellToAddToLiquidity = 100000000000000000000 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Mainnet & Testnet ETH // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function airdrop(address recipient, uint256 amount) external onlyOwner() { removeAllFee(); _transfer(_msgSender(), recipient, amount * 10**9); restoreAllFee(); } function airdropInternal(address recipient, uint256 amount) internal { removeAllFee(); _transfer(_msgSender(), recipient, amount); restoreAllFee(); } function airdropArray(address[] calldata newholders, uint256[] calldata amounts) external onlyOwner(){ uint256 iterator = 0; require(newholders.length == amounts.length, "must be the same length"); while(iterator < newholders.length){ airdropInternal(newholders[iterator], amounts[iterator] * 10**9); iterator += 1; } } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setMarketingWallet(address walletAddress) public onlyOwner { marketingWallet = walletAddress; } function upliftTxAmount() external onlyOwner() { _maxTxAmount = 10000000000000000000000 * 10**9; } function setSwapThresholdAmount(uint256 SwapThresholdAmount) external onlyOwner() { require(SwapThresholdAmount > 10000000, "Swap Threshold Amount cannot be less than 10 Million"); numTokensSellToAddToLiquidity = SwapThresholdAmount * 10**9; } function claimTokens () public onlyOwner { // make sure we capture all BNB that may or may not be sent to this contract payable(marketingWallet).transfer(address(this).balance); } function claimOtherTokens(IERC20 tokenAddress, address walletaddress) external onlyOwner() { tokenAddress.transfer(walletaddress, tokenAddress.balanceOf(address(this))); } function clearStuckBalance (address payable walletaddress) external onlyOwner() { walletaddress.transfer(address(this).balance); } function addBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = true; } function removeBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = false; } function getBotWalletStatus(address botwallet) public view returns (bool) { return botWallets[botwallet]; } function allowtrading()external onlyOwner() { canTrade = true; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves // add the marketing wallet uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); uint256 marketingshare = newBalance.mul(80).div(100); payable(marketingWallet).transfer(marketingshare); newBalance -= marketingshare; // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!canTrade){ require(sender == owner()); // only owner allowed to trade or add liquidity } if(botWallets[sender] || botWallets[recipient]){ require(botscantrade, "bots arent allowed to trade"); } if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
_tokenTransfer
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!canTrade){ require(sender == owner()); // only owner allowed to trade or add liquidity } if(botWallets[sender] || botWallets[recipient]){ require(botscantrade, "bots arent allowed to trade"); } if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); }
//this method is responsible for taking all fee, if takeFee is true
LineComment
v0.8.12+commit.f00d7308
Unlicense
ipfs://b2b19a48b15e64b681ed22c24fc3880393cdb1a9e7702562d35f7539b977bd0a
{ "func_code_index": [ 18173, 19292 ] }
60,147
DigitaloCoin
DigitaloCoin.sol
0x0387e4368bf7ddcea744c7657bd4d2168bf9a1f0
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
// Digital oCoin Token // Symbol : DoC // Name : Digital oCoin // Total supply: 21,000,000 // Decimals : 18 // // // // // // //
LineComment
totalSupply
function totalSupply() constant returns (uint256 supply) {}
/// @return total amount of tokens
NatSpecSingleLine
v0.4.25+commit.59dbf8f1
None
bzzr://f284c7a7b5e7b0db0dae7945bb5a66792751ac720a745e256c1f59454f401c21
{ "func_code_index": [ 60, 124 ] }
60,148
DigitaloCoin
DigitaloCoin.sol
0x0387e4368bf7ddcea744c7657bd4d2168bf9a1f0
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
// Digital oCoin Token // Symbol : DoC // Name : Digital oCoin // Total supply: 21,000,000 // Decimals : 18 // // // // // // //
LineComment
balanceOf
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @param _owner The address from which the balance will be retrieved /// @return The balance
NatSpecSingleLine
v0.4.25+commit.59dbf8f1
None
bzzr://f284c7a7b5e7b0db0dae7945bb5a66792751ac720a745e256c1f59454f401c21
{ "func_code_index": [ 232, 309 ] }
60,149
DigitaloCoin
DigitaloCoin.sol
0x0387e4368bf7ddcea744c7657bd4d2168bf9a1f0
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
// Digital oCoin Token // Symbol : DoC // Name : Digital oCoin // Total supply: 21,000,000 // Decimals : 18 // // // // // // //
LineComment
transfer
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.25+commit.59dbf8f1
None
bzzr://f284c7a7b5e7b0db0dae7945bb5a66792751ac720a745e256c1f59454f401c21
{ "func_code_index": [ 546, 623 ] }
60,150
DigitaloCoin
DigitaloCoin.sol
0x0387e4368bf7ddcea744c7657bd4d2168bf9a1f0
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
// Digital oCoin Token // Symbol : DoC // Name : Digital oCoin // Total supply: 21,000,000 // Decimals : 18 // // // // // // //
LineComment
transferFrom
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.25+commit.59dbf8f1
None
bzzr://f284c7a7b5e7b0db0dae7945bb5a66792751ac720a745e256c1f59454f401c21
{ "func_code_index": [ 946, 1042 ] }
60,151
DigitaloCoin
DigitaloCoin.sol
0x0387e4368bf7ddcea744c7657bd4d2168bf9a1f0
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
// Digital oCoin Token // Symbol : DoC // Name : Digital oCoin // Total supply: 21,000,000 // Decimals : 18 // // // // // // //
LineComment
approve
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not
NatSpecSingleLine
v0.4.25+commit.59dbf8f1
None
bzzr://f284c7a7b5e7b0db0dae7945bb5a66792751ac720a745e256c1f59454f401c21
{ "func_code_index": [ 1326, 1407 ] }
60,152
DigitaloCoin
DigitaloCoin.sol
0x0387e4368bf7ddcea744c7657bd4d2168bf9a1f0
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
// Digital oCoin Token // Symbol : DoC // Name : Digital oCoin // Total supply: 21,000,000 // Decimals : 18 // // // // // // //
LineComment
allowance
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
/// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent
NatSpecSingleLine
v0.4.25+commit.59dbf8f1
None
bzzr://f284c7a7b5e7b0db0dae7945bb5a66792751ac720a745e256c1f59454f401c21
{ "func_code_index": [ 1615, 1712 ] }
60,153
DigitaloCoin
DigitaloCoin.sol
0x0387e4368bf7ddcea744c7657bd4d2168bf9a1f0
Solidity
DigitaloCoin
contract DigitaloCoin is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function DigitaloCoin() { balances[msg.sender] = 21000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 21000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "DigitaloCoin"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "DoC"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 100000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
DigitaloCoin
function DigitaloCoin() { balances[msg.sender] = 21000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 21000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "DigitaloCoin"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "DoC"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 100000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH }
// Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above
LineComment
v0.4.25+commit.59dbf8f1
None
bzzr://f284c7a7b5e7b0db0dae7945bb5a66792751ac720a745e256c1f59454f401c21
{ "func_code_index": [ 1200, 2226 ] }
60,154
DigitaloCoin
DigitaloCoin.sol
0x0387e4368bf7ddcea744c7657bd4d2168bf9a1f0
Solidity
DigitaloCoin
contract DigitaloCoin is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function DigitaloCoin() { balances[msg.sender] = 21000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 21000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "DigitaloCoin"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "DoC"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 100000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; }
/* Approves and then calls the receiving contract */
Comment
v0.4.25+commit.59dbf8f1
None
bzzr://f284c7a7b5e7b0db0dae7945bb5a66792751ac720a745e256c1f59454f401c21
{ "func_code_index": [ 2822, 3627 ] }
60,155
OptaToken
OptaToken.sol
0x3fe2ef1dfb1595195768627d16751d552586dce8
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
totalSupply
function totalSupply() constant returns (uint256 supply) {}
/// @return total amount of tokens
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://8955b8b8691c20c5cd094495c8b5705abd5405beacad82a46a098a3baf7898e8
{ "func_code_index": [ 61, 125 ] }
60,156
OptaToken
OptaToken.sol
0x3fe2ef1dfb1595195768627d16751d552586dce8
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
balanceOf
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @param _owner The address from which the balance will be retrieved /// @return The balance
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://8955b8b8691c20c5cd094495c8b5705abd5405beacad82a46a098a3baf7898e8
{ "func_code_index": [ 234, 311 ] }
60,157
OptaToken
OptaToken.sol
0x3fe2ef1dfb1595195768627d16751d552586dce8
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transfer
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://8955b8b8691c20c5cd094495c8b5705abd5405beacad82a46a098a3baf7898e8
{ "func_code_index": [ 549, 626 ] }
60,158
OptaToken
OptaToken.sol
0x3fe2ef1dfb1595195768627d16751d552586dce8
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://8955b8b8691c20c5cd094495c8b5705abd5405beacad82a46a098a3baf7898e8
{ "func_code_index": [ 950, 1046 ] }
60,159
OptaToken
OptaToken.sol
0x3fe2ef1dfb1595195768627d16751d552586dce8
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
approve
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://8955b8b8691c20c5cd094495c8b5705abd5405beacad82a46a098a3baf7898e8
{ "func_code_index": [ 1331, 1412 ] }
60,160