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
BondingShareV2
contracts/interfaces/IMasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
IMasterChefV2
interface IMasterChefV2 { struct BondingShareInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accuGOVPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 amount, uint256 bondingShareID); event Withdraw( address indexed user, uint256 amount, uint256 bondingShareID ); function deposit( address sender, uint256 amount, uint256 bondingShareID ) external; // Withdraw LP tokens from MasterChef. function withdraw( address sender, uint256 amount, uint256 bondingShareID ) external; // Info about a bondinh share function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory); // Total amount of shares function totalShares() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingUGOV(address _user) external view returns (uint256); }
getBondingShareInfo
function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory);
// Info about a bondinh share
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 909, 1021 ] }
3,307
BondingShareV2
contracts/interfaces/IMasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
IMasterChefV2
interface IMasterChefV2 { struct BondingShareInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accuGOVPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 amount, uint256 bondingShareID); event Withdraw( address indexed user, uint256 amount, uint256 bondingShareID ); function deposit( address sender, uint256 amount, uint256 bondingShareID ) external; // Withdraw LP tokens from MasterChef. function withdraw( address sender, uint256 amount, uint256 bondingShareID ) external; // Info about a bondinh share function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory); // Total amount of shares function totalShares() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingUGOV(address _user) external view returns (uint256); }
totalShares
function totalShares() external view returns (uint256);
// Total amount of shares
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1053, 1112 ] }
3,308
BondingShareV2
contracts/interfaces/IMasterChefV2.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
IMasterChefV2
interface IMasterChefV2 { struct BondingShareInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accuGOVPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 amount, uint256 bondingShareID); event Withdraw( address indexed user, uint256 amount, uint256 bondingShareID ); function deposit( address sender, uint256 amount, uint256 bondingShareID ) external; // Withdraw LP tokens from MasterChef. function withdraw( address sender, uint256 amount, uint256 bondingShareID ) external; // Info about a bondinh share function getBondingShareInfo(uint256 _id) external view returns (uint256[2] memory); // Total amount of shares function totalShares() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingUGOV(address _user) external view returns (uint256); }
pendingUGOV
function pendingUGOV(address _user) external view returns (uint256);
// View function to see pending SUSHIs on frontend.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1170, 1242 ] }
3,309
Creatures
DegensFarmBase.sol
0xd227df494367a8b769b4bf2bbebd0388a8758741
Solidity
DegenFarmBase
abstract contract DegenFarmBase is ERC1155Receiver, Ownable { enum AnimalType { Cow, Horse, Rabbit, Chicken, Pig, Cat, Dog, Goose, Goat, Sheep, Snake, Fish, Frog, Worm, Lama, Mouse, Camel, Donkey, Bee, Duck, GenesisEgg // 20 } enum Rarity { Normie, // 0 Chad, // 1 Degen, // 2 Unique // 3 } enum Result {Fail, Dung, Chad, Degen} //External conatrct addresses used with this farm. struct AddressRegistry { address land; address creatures; address inventory; address bagstoken; address dungtoken; } //Degens Farm Key numbers struct CreaturesCount { uint16 totalNormie; uint16 leftNormie; uint16 totalChad; uint16 leftChadToDiscover; uint16 totalDegen; uint16 leftDegenToDiscover; uint16 leftChadFarmAttempts; uint16 leftDegenFarmAttempts; } //Land count record struct LandCount { uint16 total; uint16 left; } // Record represent one farming act struct FarmRecord { uint256 creatureId; uint256 landId; uint256 harvestTime; uint256[] amuletsPrice1; uint256[] amuletsPrice2; Result harvest; uint256 harvestId; //new NFT tokenId bool[3] commonAmuletInitialHold; } // Bonus for better harvest struct Bonus { uint16 amuletHold; uint16 amuletBullTrend; uint16 inventoryHold; } uint8 constant public CREATURE_TYPE_COUNT_MAX = 20; //how much creatures types may be used //Creature probubility multiplier, scaled with 100. 3.00 - 300, 3.05 - 305 etc // so we need additional divide on 100 in formula uint32 constant public CREATURE_P_MULT = 230; uint16 public MAX_ALL_NORMIES = getCreatureTypeCount() * getNormieCountInType(); //subj uint256 constant public NFT_ID_MULTIPLIER = 10000; //must be set more then all Normies count uint256 constant public FARM_DUNG_AMOUNT = 250e32; //per one harvest uint16 constant public BONUS_POINTS_AMULET_HOLD = 10; uint16 constant public BONUS_POINTS_AMULET_BULL_TREND = 90; //Common Amulet addresses address[3] public COMMON_AMULETS = [ 0xa0246c9032bC3A600820415aE600c6388619A14D, 0x87d73E916D7057945c9BcD8cdd94e42A6F47f776, 0x126c121f99e1E211dF2e5f8De2d96Fa36647c855 ]; bool public REVEAL_ENABLED = false; bool public FARMING_ENABLED = false; address public priceProvider; IEggs public eggs; address[][CREATURE_TYPE_COUNT_MAX] public amulets; //amulets for creatures AddressRegistry public farm; LandCount public landCount; //common token price snapshots mapping(uint256 => uint256[3]) public commonAmuletPrices; mapping(address => uint256) public maxAmuletBalances; // mapping from user to his(her) staked tools // Index of uint256[6] represent tool NFT itemID mapping(address => uint256[6]) public userStakedTools; uint16 public allNormiesesLeft; CreaturesCount[CREATURE_TYPE_COUNT_MAX] public creaturesBorn; FarmRecord[] farming; event Reveal(uint256 indexed _tokenId, bool _isCreature, uint8 _animalType); event Harvest( uint256 indexed _eggId, address farmer, uint8 result , uint16 baseChance, uint16 amuletHold, uint16 amuletBullTrend, uint16 inventoryHold ); constructor ( address _land, address _creatures, address _inventory, address _bagstoken, address _dungtoken, IEggs _eggs ) { farm.land = _land; farm.creatures = _creatures; farm.inventory = _inventory; farm.bagstoken = _bagstoken; farm.dungtoken = _dungtoken; // Index of creaturesBorn in this initial setting // must NOT exceed CREATURE_TYPE_COUNT for (uint i = 0; i < getCreatureTypeCount(); i++) { creaturesBorn[i] = CreaturesCount( getNormieCountInType(), // totalNormie; getNormieCountInType(), // leftNormie; getChadCountInType(), // totalChad; getChadCountInType(), // leftChadToDiscover; 1, // totalDegen; 1, // leftDegenToDiscover; getNormieCountInType(), // leftChadFarmAttempts; getChadCountInType()); // leftDegenFarmAttempts; } landCount = LandCount(getMaxLands(), getMaxLands()); allNormiesesLeft = MAX_ALL_NORMIES; eggs = _eggs; } /** * @dev Changes inventory contract */ function setInventory(address _inventory) external onlyOwner { farm.inventory = _inventory; } function reveal(uint count) external { require(_isRevelEnabled(), "Please wait for reveal enabled."); require(count > 0, "Count must be positive"); require(count <= 8, "Count must less than 9"); // random limit require( IERC20(farm.bagstoken).allowance(msg.sender, address(this)) >= count*1, "Please approve your BAGS token to this contract." ); require( IERC20(farm.bagstoken).transferFrom(msg.sender, address(this), count*1) ); uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); // random seed for 8 reveals (8x32=256) for (uint i = 0; i < count; i++) { _reveal(randomSeed); randomSeed = randomSeed / 0x100000000; // shift right 32 bits } } event Log(string mess); /** * @dev Start farming process. New NFT - Egg will minted for user * @param _creatureId - NFT tokenId, caller must be owner of this token * @param _landId -- NFT tokenId, caller must be owner of this token */ function farmDeploy(uint256 _creatureId, uint256 _landId) external { require(FARMING_ENABLED == true, "Chief Farmer not enable yet"); require(ICreatures(farm.creatures).ownerOf(_creatureId) == msg.sender, "Need to be Creature Owner" ); require(ILand(farm.land).ownerOf(_landId) == msg.sender, "Need to be Land Owner" ); (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity(_creatureId); require((DegenFarmBase.Rarity)(crRarity) == Rarity.Normie || (DegenFarmBase.Rarity)(crRarity) == Rarity.Chad, "Can farm only Normie and Chad"); //Check that farming available yet if (crRarity == 0) { require(creaturesBorn[crType].leftChadToDiscover > 0, "No more chads left"); } else { require(creaturesBorn[crType].leftDegenToDiscover > 0, "No more Degen left"); } //1. Lets make amulet price snapshot //1.1. First we need creat array with properly elements count uint256[] memory prices1 = new uint256[](amulets[crType].length); uint256[] memory prices2 = new uint256[](amulets[crType].length); prices1 = _getExistingAmuletsPrices(amulets[crType]); //2.Check and save Common Amulets price(if not exist yet) _saveCommonAmuletPrices(block.timestamp); //3. Save deploy record farming.push( FarmRecord({ creatureId: _creatureId, landId: _landId, harvestTime: block.timestamp + getFarmingDuration(), amuletsPrice1: prices1, amuletsPrice2: prices2, harvest: Result.Fail, harvestId: 0, commonAmuletInitialHold: _getCommonAmuletsHoldState(msg.sender) //save initial hold state }) ); // Let's mint Egg. eggs.mint( msg.sender, // farmer farming.length - 1 // tokenId ); //STAKE LAND and Creatures!!!! ILand(farm.land).transferFrom(msg.sender, address(this), _landId); ICreatures(farm.creatures).transferFrom(msg.sender, address(this), _creatureId); } /** * @dev Finish farming process. Egg NFT will be burn * @param _deployId - NFT tokenId, caller must be owner of this token */ function harvest(uint256 _deployId) external { require(eggs.ownerOf(_deployId) == msg.sender, "This is NOT YOUR EGG"); FarmRecord storage f = farming[_deployId]; require(f.harvestTime <= block.timestamp, "To early for harvest"); //Lets Calculate Dung/CHAD-DEGEN chance Result farmingResult; Bonus memory bonus; //1. BaseChance (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity( f.creatureId ); uint16 baseChance; if (crRarity == 0) { //Try farm CHAD. So if there is no CHADs any more we must return assets if (creaturesBorn[crType].leftChadToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftChadToDiscover * 100 /(creaturesBorn[crType].leftChadFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftChadFarmAttempts -= 1; } else { //Try farm DEGEN. So if there is no DEGENSs any more we must return assets if (creaturesBorn[crType].leftDegenToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftDegenToDiscover * 100 /(creaturesBorn[crType].leftDegenFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftDegenFarmAttempts -= 1; } ////////////////////////////////////////////// // 2. Bonus for amulet token ***HOLD*** // 3. Bonus for amulets BULLs trend ////////////////////////////////////////////// bonus.amuletHold = 0; bonus.amuletBullTrend = 0; //Check common amulets _saveCommonAmuletPrices(block.timestamp); //Get current hold stae for (uint8 i = 0; i < COMMON_AMULETS.length; i ++){ if (f.commonAmuletInitialHold[i] && _getCommonAmuletsHoldState(msg.sender)[i]) { //token was hold at deploy time and now - iT IS GOOD //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(COMMON_AMULETS[i]); bonus.amuletHold = uint16( IERC20(COMMON_AMULETS[i]).balanceOf(msg.sender) * 100 / maxAmuletBalances[COMMON_AMULETS[i]] * BONUS_POINTS_AMULET_HOLD / 100 //100 used for scale ); //Lets check Bull TREND if (_getCommonAmuletPrices(f.harvestTime - getFarmingDuration())[i] < _getCommonAmuletPrices(block.timestamp)[i] ) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } //Ok, if there is NO common amulets lets check personal uint256[] memory prices2 = new uint256[](amulets[crType].length); prices2 = _getExistingAmuletsPrices(amulets[crType]); if (bonus.amuletHold != BONUS_POINTS_AMULET_HOLD) { for (uint8 i=0; i < f.amuletsPrice1.length; i ++){ if (f.amuletsPrice1[i] > 0 && prices2[i] > 0){ //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(amulets[i][crType]); bonus.amuletHold = uint16( IERC20(amulets[i][crType]).balanceOf(msg.sender) * 100 //100 used for scale / maxAmuletBalances[amulets[i][crType]] * BONUS_POINTS_AMULET_HOLD /100 ); //Lets check Bull TREND if (f.amuletsPrice1[i] < prices2[i]) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } } ////////////////////////////////////////////// ////////////////////////////////////////////// //4. Bonus for inventory ////////////////////////////////////////////// bonus.inventoryHold = 0; if (userStakedTools[msg.sender].length > 0) { for (uint8 i=0; i<userStakedTools[msg.sender].length; i++) { if (userStakedTools[msg.sender][i] > 0){ bonus.inventoryHold = bonus.inventoryHold + IInventory(farm.inventory).getToolBoost(i); } } } ////////////////////////////////////////////// uint16 allBonus = bonus.amuletHold + bonus.amuletBullTrend + bonus.inventoryHold; uint8 chanceOfRarityUP = uint8( (baseChance + allBonus) * 100 / (100 + allBonus) ); uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = chanceOfRarityUP; choiceWeight[1] = 100 - chanceOfRarityUP; uint8 choice = uint8(_getWeightedChoice(choiceWeight)); if (choice == 0) { f.harvestId = (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId; // Mint new chad/degen uint32 index; //Decrease appropriate CREATRURE COUNT if (crRarity + 1 == uint8(Rarity.Chad)) { index = creaturesBorn[crType].totalChad - creaturesBorn[crType].leftChadToDiscover + 1; creaturesBorn[crType].leftChadToDiscover -= 1; farmingResult = Result.Chad; } else if (crRarity + 1 == uint8(Rarity.Degen)) { index = creaturesBorn[crType].totalDegen - creaturesBorn[crType].leftDegenToDiscover + 1; creaturesBorn[crType].leftDegenToDiscover -= 1; farmingResult = Result.Degen; } ICreatures(farm.creatures).mint( msg.sender, (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId, // new iD crType, //AnimalType crRarity + 1, index // index ); } else { //Mint new dung IDung(farm.dungtoken).mint(msg.sender, FARM_DUNG_AMOUNT); farmingResult = Result.Dung; } //BURN Land ILand(farm.land).burn(f.landId); _endFarming(_deployId, farmingResult); emit Harvest( _deployId, msg.sender, uint8(farmingResult), baseChance, bonus.amuletHold, bonus.amuletBullTrend, bonus.inventoryHold ); } /** * @dev Stake one inventory item * @param _itemId - NFT tokenId, caller must be owner of this token */ function stakeOneTool(uint8 _itemId) external { _stakeOneTool(_itemId); } /** * @dev UnStake one inventory item * @param _itemId - NFT tokenId */ function unstakeOneTool(uint8 _itemId) external { _unstakeOneTool(_itemId); } ///////////////////////////////////////////////////// //// Admin functions /////// ///////////////////////////////////////////////////// function setOneCommonAmulet(uint8 _index, address _token) external onlyOwner { COMMON_AMULETS[_index] = _token; } function setAmuletForOneCreature(uint8 _index, address[] memory _tokens) external onlyOwner { delete amulets[_index]; amulets[_index] = _tokens; } function setPriceProvider(address _priceProvider) external onlyOwner { priceProvider = _priceProvider; } function enableReveal(bool _isEnabled) external onlyOwner { REVEAL_ENABLED = _isEnabled; } function enableFarming(bool _isEnabled) external onlyOwner { FARMING_ENABLED = _isEnabled; } //////////////////////////////////////// /// Proxy for NFT Operators mamnage // //////////////////////////////////////// function addOperator(address _contract, address newOperator) external onlyOwner { IOperatorManage(_contract).addOperator(newOperator); } function removeOperator(address _contract, address oldOperator) external onlyOwner { IOperatorManage(_contract).removeOperator(oldOperator); } function reclaimToken(address _contract, IERC20 anyTokens, address _admin) external onlyOwner { IOperatorManage(_contract).withdrawERC20(anyTokens, _admin); } //////////////////////////////////////////////////////// function getCreatureAmulets(uint8 _creatureType) external view returns (address[] memory) { return _getCreatureAmulets(_creatureType); } function _getCreatureAmulets(uint8 _creatureType) internal view returns (address[] memory) { return amulets[_creatureType]; } function getCreatureStat(uint8 _creatureType) external view returns ( uint16, uint16, uint16, uint16, uint16, uint16, uint16, uint16 ) { CreaturesCount storage stat = creaturesBorn[_creatureType]; return ( stat.totalNormie, stat.leftNormie, stat.totalChad, stat.leftChadToDiscover, stat.totalDegen, stat.leftDegenToDiscover, stat.leftChadFarmAttempts, stat.leftDegenFarmAttempts ); } function getWeightedChoice(uint8[] memory _weights) external view returns (uint8){ return _getWeightedChoice(_weights); } function _getWeightedChoice(uint8[] memory _weights) internal view returns (uint8){ uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); return _getWeightedChoice2(_weights, randomSeed); } function getFarmingById(uint256 _farmingId) external view returns (FarmRecord memory) { return farming[_farmingId]; } function getCommonAmuletPrices(uint256 _timestamp) external view returns (uint256[3] memory) { return _getCommonAmuletPrices(_timestamp); } function getOneAmuletPrice(address _token) external view returns (uint256) { return _getOneAmuletPrice(_token); } /////////////////////////////////////////////// /// Internals /////// /////////////////////////////////////////////// /** * @dev Save farming results in storage and mint * appropriate token (NFT, ERC20 or None) */ function _endFarming(uint256 _deployId, Result _res) internal { //TODO need refactor if EGGs will be FarmRecord storage f = farming[_deployId]; f.harvest = _res; // unstake creature ICreatures(farm.creatures).transferFrom(address(this), msg.sender, f.creatureId); eggs.burn(_deployId); // Burn EGG if (_res == Result.Fail) { //unstake land (if staked) if (ILand(farm.land).ownerOf(f.landId) == address(this)){ ILand(farm.land).transferFrom(address(this), msg.sender, f.landId); } emit Harvest( _deployId, msg.sender, uint8(_res), 0, //baseChance 0, //bonus.amuletHold, 0, //bonus.amuletBullTrend, 0 //bonus.inventoryHold ); } } function _stakeOneTool(uint8 _itemId) internal { require(IInventory(farm.inventory).balanceOf(msg.sender, _itemId) >= 1, "You must own this tool for stake!" ); //Before stake we need two checks. //1. Removed //2. Cant`t stake one tool more than one item require(userStakedTools[msg.sender][_itemId] == 0, "Tool is already staked"); //stake IInventory(farm.inventory).safeTransferFrom( msg.sender, address(this), _itemId, 1, bytes('0') ); userStakedTools[msg.sender][_itemId] = block.timestamp; } function _unstakeOneTool(uint8 _itemId) internal { require(userStakedTools[msg.sender][_itemId] > 0, "This tool is not staked yet"); require(block.timestamp - userStakedTools[msg.sender][_itemId] >= getToolUnstakeDelay(), "Cant unstake earlier than a week" ); userStakedTools[msg.sender][_itemId] = 0; IInventory(farm.inventory).safeTransferFrom( address(this), msg.sender, _itemId, 1, bytes('0') ); } function _saveCommonAmuletPrices(uint256 _timestamp) internal { //Lets check if price NOT exist for this timestamp - lets save it if (commonAmuletPrices[_timestamp][0] == 0) { for (uint8 i=0; i < COMMON_AMULETS.length; i++){ commonAmuletPrices[_timestamp][i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } } } function _checkAndSaveMaxAmuletPrice(address _amulet) internal { if (IERC20(_amulet).balanceOf(msg.sender) > maxAmuletBalances[_amulet] ) { maxAmuletBalances[_amulet] = IERC20(_amulet).balanceOf(msg.sender); } } function _getCommonAmuletPrices(uint256 _timestamp) internal view returns (uint256[3] memory) { //Lets check if price allready exist for this timestamp - just return it if (commonAmuletPrices[_timestamp][0] != 0) { return commonAmuletPrices[_timestamp]; } //If price is not exist lets get it from oracles uint256[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ res[i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } return res; } function _getCommonAmuletsHoldState(address _farmer) internal view returns (bool[3] memory) { //If token balance =0 - set false bool[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ if (IERC20(COMMON_AMULETS[i]).balanceOf(_farmer) > 0){ res[i] = true; } else { // Set to zero if token balance is 0 res[i] = false; } } return res; } function _getExistingAmuletsPrices(address[] memory _tokens) internal view returns (uint256[] memory) { uint256[] memory res = new uint256[](_tokens.length); for (uint8 i=0; i < _tokens.length; i++){ if (IERC20(_tokens[i]).balanceOf(msg.sender) > 0){ res[i] = _getOneAmuletPrice(_tokens[i]); } else { // Set to zero if token balance is 0 res[i] = 0; } } return res; } function _getOneAmuletPrice(address _token) internal view returns (uint256) { return IAmuletPriceProvider(priceProvider).getLastPrice(_token); } function _isRevelEnabled() internal view returns (bool) { return REVEAL_ENABLED; } function _reveal(uint randomSeed) internal { require ((landCount.left + allNormiesesLeft) > 0, "Sorry, no more reveal!"); //1. Lets choose Land OR Creature, % //So we have two possible results. 1 - Land, 0 - Creature. // sum of weights = 100, lets define weigth for Creature uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = uint8( uint32(allNormiesesLeft) * CREATURE_P_MULT // * 100 removed due CREATURE_P_MULT / (CREATURE_P_MULT * uint32(allNormiesesLeft) / 100 + uint32(landCount.left)) ); choiceWeight[1] = 100 - choiceWeight[0]; uint8 choice = uint8(_getWeightedChoice2(choiceWeight, randomSeed)); //Check that choice can be executed if (choice != 0 && landCount.left == 0) { //There are no more Lands. So we need change choice choice = 0; } if (choice == 0) { // create creature uint8[] memory choiceWeight0 = new uint8[](getCreatureTypeCount()); //2. Ok, Creature will be born. But what kind of? for (uint8 i = 0; i < getCreatureTypeCount(); i ++) { choiceWeight0[i] = uint8(creaturesBorn[i].leftNormie); } choice = uint8(_getWeightedChoice2(choiceWeight0, randomSeed / 0x10000)); // shift right 16 bits ICreatures(farm.creatures).mint( msg.sender, MAX_ALL_NORMIES - allNormiesesLeft, choice, //AnimalType 0, creaturesBorn[choice].totalNormie - creaturesBorn[choice].leftNormie + 1 // index ); emit Reveal(MAX_ALL_NORMIES - allNormiesesLeft, true, choice); allNormiesesLeft -= 1; creaturesBorn[choice].leftNormie -= 1; } else { // create land ILand(farm.land).mint( msg.sender, getMaxLands() - landCount.left ); emit Reveal(getMaxLands() - landCount.left , false, 0); landCount.left -= 1; } } function _getWeightedChoice2(uint8[] memory _weights, uint randomSeed) internal view returns (uint8){ uint256 sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { sum_of_weights += _weights[i]; } uint256 rnd = randomSeed % sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { if (rnd < _weights[i]) { return i; } rnd -= _weights[i]; } return 0; } /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); } /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)")); } function getCreatureTypeCount() virtual internal view returns (uint16); function getFarmingDuration() virtual internal view returns (uint); function getToolUnstakeDelay() virtual internal view returns (uint); function getNormieCountInType() virtual internal view returns (uint16); function getChadCountInType() virtual internal view returns (uint16); function getMaxLands() virtual internal view returns (uint16); function getUsersTokens(address _owner) external view returns (uint256[] memory) { return eggs.getUsersTokens(_owner); } }
setInventory
function setInventory(address _inventory) external onlyOwner { farm.inventory = _inventory; }
/** * @dev Changes inventory contract */
NatSpecMultiLine
v0.7.4+commit.3f05b770
MIT
ipfs://308c7d0f38216f626771d86f2b5b3091893bd5f12659a801a1f13db0060ec78f
{ "func_code_index": [ 5026, 5138 ] }
3,310
Creatures
DegensFarmBase.sol
0xd227df494367a8b769b4bf2bbebd0388a8758741
Solidity
DegenFarmBase
abstract contract DegenFarmBase is ERC1155Receiver, Ownable { enum AnimalType { Cow, Horse, Rabbit, Chicken, Pig, Cat, Dog, Goose, Goat, Sheep, Snake, Fish, Frog, Worm, Lama, Mouse, Camel, Donkey, Bee, Duck, GenesisEgg // 20 } enum Rarity { Normie, // 0 Chad, // 1 Degen, // 2 Unique // 3 } enum Result {Fail, Dung, Chad, Degen} //External conatrct addresses used with this farm. struct AddressRegistry { address land; address creatures; address inventory; address bagstoken; address dungtoken; } //Degens Farm Key numbers struct CreaturesCount { uint16 totalNormie; uint16 leftNormie; uint16 totalChad; uint16 leftChadToDiscover; uint16 totalDegen; uint16 leftDegenToDiscover; uint16 leftChadFarmAttempts; uint16 leftDegenFarmAttempts; } //Land count record struct LandCount { uint16 total; uint16 left; } // Record represent one farming act struct FarmRecord { uint256 creatureId; uint256 landId; uint256 harvestTime; uint256[] amuletsPrice1; uint256[] amuletsPrice2; Result harvest; uint256 harvestId; //new NFT tokenId bool[3] commonAmuletInitialHold; } // Bonus for better harvest struct Bonus { uint16 amuletHold; uint16 amuletBullTrend; uint16 inventoryHold; } uint8 constant public CREATURE_TYPE_COUNT_MAX = 20; //how much creatures types may be used //Creature probubility multiplier, scaled with 100. 3.00 - 300, 3.05 - 305 etc // so we need additional divide on 100 in formula uint32 constant public CREATURE_P_MULT = 230; uint16 public MAX_ALL_NORMIES = getCreatureTypeCount() * getNormieCountInType(); //subj uint256 constant public NFT_ID_MULTIPLIER = 10000; //must be set more then all Normies count uint256 constant public FARM_DUNG_AMOUNT = 250e32; //per one harvest uint16 constant public BONUS_POINTS_AMULET_HOLD = 10; uint16 constant public BONUS_POINTS_AMULET_BULL_TREND = 90; //Common Amulet addresses address[3] public COMMON_AMULETS = [ 0xa0246c9032bC3A600820415aE600c6388619A14D, 0x87d73E916D7057945c9BcD8cdd94e42A6F47f776, 0x126c121f99e1E211dF2e5f8De2d96Fa36647c855 ]; bool public REVEAL_ENABLED = false; bool public FARMING_ENABLED = false; address public priceProvider; IEggs public eggs; address[][CREATURE_TYPE_COUNT_MAX] public amulets; //amulets for creatures AddressRegistry public farm; LandCount public landCount; //common token price snapshots mapping(uint256 => uint256[3]) public commonAmuletPrices; mapping(address => uint256) public maxAmuletBalances; // mapping from user to his(her) staked tools // Index of uint256[6] represent tool NFT itemID mapping(address => uint256[6]) public userStakedTools; uint16 public allNormiesesLeft; CreaturesCount[CREATURE_TYPE_COUNT_MAX] public creaturesBorn; FarmRecord[] farming; event Reveal(uint256 indexed _tokenId, bool _isCreature, uint8 _animalType); event Harvest( uint256 indexed _eggId, address farmer, uint8 result , uint16 baseChance, uint16 amuletHold, uint16 amuletBullTrend, uint16 inventoryHold ); constructor ( address _land, address _creatures, address _inventory, address _bagstoken, address _dungtoken, IEggs _eggs ) { farm.land = _land; farm.creatures = _creatures; farm.inventory = _inventory; farm.bagstoken = _bagstoken; farm.dungtoken = _dungtoken; // Index of creaturesBorn in this initial setting // must NOT exceed CREATURE_TYPE_COUNT for (uint i = 0; i < getCreatureTypeCount(); i++) { creaturesBorn[i] = CreaturesCount( getNormieCountInType(), // totalNormie; getNormieCountInType(), // leftNormie; getChadCountInType(), // totalChad; getChadCountInType(), // leftChadToDiscover; 1, // totalDegen; 1, // leftDegenToDiscover; getNormieCountInType(), // leftChadFarmAttempts; getChadCountInType()); // leftDegenFarmAttempts; } landCount = LandCount(getMaxLands(), getMaxLands()); allNormiesesLeft = MAX_ALL_NORMIES; eggs = _eggs; } /** * @dev Changes inventory contract */ function setInventory(address _inventory) external onlyOwner { farm.inventory = _inventory; } function reveal(uint count) external { require(_isRevelEnabled(), "Please wait for reveal enabled."); require(count > 0, "Count must be positive"); require(count <= 8, "Count must less than 9"); // random limit require( IERC20(farm.bagstoken).allowance(msg.sender, address(this)) >= count*1, "Please approve your BAGS token to this contract." ); require( IERC20(farm.bagstoken).transferFrom(msg.sender, address(this), count*1) ); uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); // random seed for 8 reveals (8x32=256) for (uint i = 0; i < count; i++) { _reveal(randomSeed); randomSeed = randomSeed / 0x100000000; // shift right 32 bits } } event Log(string mess); /** * @dev Start farming process. New NFT - Egg will minted for user * @param _creatureId - NFT tokenId, caller must be owner of this token * @param _landId -- NFT tokenId, caller must be owner of this token */ function farmDeploy(uint256 _creatureId, uint256 _landId) external { require(FARMING_ENABLED == true, "Chief Farmer not enable yet"); require(ICreatures(farm.creatures).ownerOf(_creatureId) == msg.sender, "Need to be Creature Owner" ); require(ILand(farm.land).ownerOf(_landId) == msg.sender, "Need to be Land Owner" ); (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity(_creatureId); require((DegenFarmBase.Rarity)(crRarity) == Rarity.Normie || (DegenFarmBase.Rarity)(crRarity) == Rarity.Chad, "Can farm only Normie and Chad"); //Check that farming available yet if (crRarity == 0) { require(creaturesBorn[crType].leftChadToDiscover > 0, "No more chads left"); } else { require(creaturesBorn[crType].leftDegenToDiscover > 0, "No more Degen left"); } //1. Lets make amulet price snapshot //1.1. First we need creat array with properly elements count uint256[] memory prices1 = new uint256[](amulets[crType].length); uint256[] memory prices2 = new uint256[](amulets[crType].length); prices1 = _getExistingAmuletsPrices(amulets[crType]); //2.Check and save Common Amulets price(if not exist yet) _saveCommonAmuletPrices(block.timestamp); //3. Save deploy record farming.push( FarmRecord({ creatureId: _creatureId, landId: _landId, harvestTime: block.timestamp + getFarmingDuration(), amuletsPrice1: prices1, amuletsPrice2: prices2, harvest: Result.Fail, harvestId: 0, commonAmuletInitialHold: _getCommonAmuletsHoldState(msg.sender) //save initial hold state }) ); // Let's mint Egg. eggs.mint( msg.sender, // farmer farming.length - 1 // tokenId ); //STAKE LAND and Creatures!!!! ILand(farm.land).transferFrom(msg.sender, address(this), _landId); ICreatures(farm.creatures).transferFrom(msg.sender, address(this), _creatureId); } /** * @dev Finish farming process. Egg NFT will be burn * @param _deployId - NFT tokenId, caller must be owner of this token */ function harvest(uint256 _deployId) external { require(eggs.ownerOf(_deployId) == msg.sender, "This is NOT YOUR EGG"); FarmRecord storage f = farming[_deployId]; require(f.harvestTime <= block.timestamp, "To early for harvest"); //Lets Calculate Dung/CHAD-DEGEN chance Result farmingResult; Bonus memory bonus; //1. BaseChance (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity( f.creatureId ); uint16 baseChance; if (crRarity == 0) { //Try farm CHAD. So if there is no CHADs any more we must return assets if (creaturesBorn[crType].leftChadToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftChadToDiscover * 100 /(creaturesBorn[crType].leftChadFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftChadFarmAttempts -= 1; } else { //Try farm DEGEN. So if there is no DEGENSs any more we must return assets if (creaturesBorn[crType].leftDegenToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftDegenToDiscover * 100 /(creaturesBorn[crType].leftDegenFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftDegenFarmAttempts -= 1; } ////////////////////////////////////////////// // 2. Bonus for amulet token ***HOLD*** // 3. Bonus for amulets BULLs trend ////////////////////////////////////////////// bonus.amuletHold = 0; bonus.amuletBullTrend = 0; //Check common amulets _saveCommonAmuletPrices(block.timestamp); //Get current hold stae for (uint8 i = 0; i < COMMON_AMULETS.length; i ++){ if (f.commonAmuletInitialHold[i] && _getCommonAmuletsHoldState(msg.sender)[i]) { //token was hold at deploy time and now - iT IS GOOD //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(COMMON_AMULETS[i]); bonus.amuletHold = uint16( IERC20(COMMON_AMULETS[i]).balanceOf(msg.sender) * 100 / maxAmuletBalances[COMMON_AMULETS[i]] * BONUS_POINTS_AMULET_HOLD / 100 //100 used for scale ); //Lets check Bull TREND if (_getCommonAmuletPrices(f.harvestTime - getFarmingDuration())[i] < _getCommonAmuletPrices(block.timestamp)[i] ) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } //Ok, if there is NO common amulets lets check personal uint256[] memory prices2 = new uint256[](amulets[crType].length); prices2 = _getExistingAmuletsPrices(amulets[crType]); if (bonus.amuletHold != BONUS_POINTS_AMULET_HOLD) { for (uint8 i=0; i < f.amuletsPrice1.length; i ++){ if (f.amuletsPrice1[i] > 0 && prices2[i] > 0){ //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(amulets[i][crType]); bonus.amuletHold = uint16( IERC20(amulets[i][crType]).balanceOf(msg.sender) * 100 //100 used for scale / maxAmuletBalances[amulets[i][crType]] * BONUS_POINTS_AMULET_HOLD /100 ); //Lets check Bull TREND if (f.amuletsPrice1[i] < prices2[i]) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } } ////////////////////////////////////////////// ////////////////////////////////////////////// //4. Bonus for inventory ////////////////////////////////////////////// bonus.inventoryHold = 0; if (userStakedTools[msg.sender].length > 0) { for (uint8 i=0; i<userStakedTools[msg.sender].length; i++) { if (userStakedTools[msg.sender][i] > 0){ bonus.inventoryHold = bonus.inventoryHold + IInventory(farm.inventory).getToolBoost(i); } } } ////////////////////////////////////////////// uint16 allBonus = bonus.amuletHold + bonus.amuletBullTrend + bonus.inventoryHold; uint8 chanceOfRarityUP = uint8( (baseChance + allBonus) * 100 / (100 + allBonus) ); uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = chanceOfRarityUP; choiceWeight[1] = 100 - chanceOfRarityUP; uint8 choice = uint8(_getWeightedChoice(choiceWeight)); if (choice == 0) { f.harvestId = (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId; // Mint new chad/degen uint32 index; //Decrease appropriate CREATRURE COUNT if (crRarity + 1 == uint8(Rarity.Chad)) { index = creaturesBorn[crType].totalChad - creaturesBorn[crType].leftChadToDiscover + 1; creaturesBorn[crType].leftChadToDiscover -= 1; farmingResult = Result.Chad; } else if (crRarity + 1 == uint8(Rarity.Degen)) { index = creaturesBorn[crType].totalDegen - creaturesBorn[crType].leftDegenToDiscover + 1; creaturesBorn[crType].leftDegenToDiscover -= 1; farmingResult = Result.Degen; } ICreatures(farm.creatures).mint( msg.sender, (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId, // new iD crType, //AnimalType crRarity + 1, index // index ); } else { //Mint new dung IDung(farm.dungtoken).mint(msg.sender, FARM_DUNG_AMOUNT); farmingResult = Result.Dung; } //BURN Land ILand(farm.land).burn(f.landId); _endFarming(_deployId, farmingResult); emit Harvest( _deployId, msg.sender, uint8(farmingResult), baseChance, bonus.amuletHold, bonus.amuletBullTrend, bonus.inventoryHold ); } /** * @dev Stake one inventory item * @param _itemId - NFT tokenId, caller must be owner of this token */ function stakeOneTool(uint8 _itemId) external { _stakeOneTool(_itemId); } /** * @dev UnStake one inventory item * @param _itemId - NFT tokenId */ function unstakeOneTool(uint8 _itemId) external { _unstakeOneTool(_itemId); } ///////////////////////////////////////////////////// //// Admin functions /////// ///////////////////////////////////////////////////// function setOneCommonAmulet(uint8 _index, address _token) external onlyOwner { COMMON_AMULETS[_index] = _token; } function setAmuletForOneCreature(uint8 _index, address[] memory _tokens) external onlyOwner { delete amulets[_index]; amulets[_index] = _tokens; } function setPriceProvider(address _priceProvider) external onlyOwner { priceProvider = _priceProvider; } function enableReveal(bool _isEnabled) external onlyOwner { REVEAL_ENABLED = _isEnabled; } function enableFarming(bool _isEnabled) external onlyOwner { FARMING_ENABLED = _isEnabled; } //////////////////////////////////////// /// Proxy for NFT Operators mamnage // //////////////////////////////////////// function addOperator(address _contract, address newOperator) external onlyOwner { IOperatorManage(_contract).addOperator(newOperator); } function removeOperator(address _contract, address oldOperator) external onlyOwner { IOperatorManage(_contract).removeOperator(oldOperator); } function reclaimToken(address _contract, IERC20 anyTokens, address _admin) external onlyOwner { IOperatorManage(_contract).withdrawERC20(anyTokens, _admin); } //////////////////////////////////////////////////////// function getCreatureAmulets(uint8 _creatureType) external view returns (address[] memory) { return _getCreatureAmulets(_creatureType); } function _getCreatureAmulets(uint8 _creatureType) internal view returns (address[] memory) { return amulets[_creatureType]; } function getCreatureStat(uint8 _creatureType) external view returns ( uint16, uint16, uint16, uint16, uint16, uint16, uint16, uint16 ) { CreaturesCount storage stat = creaturesBorn[_creatureType]; return ( stat.totalNormie, stat.leftNormie, stat.totalChad, stat.leftChadToDiscover, stat.totalDegen, stat.leftDegenToDiscover, stat.leftChadFarmAttempts, stat.leftDegenFarmAttempts ); } function getWeightedChoice(uint8[] memory _weights) external view returns (uint8){ return _getWeightedChoice(_weights); } function _getWeightedChoice(uint8[] memory _weights) internal view returns (uint8){ uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); return _getWeightedChoice2(_weights, randomSeed); } function getFarmingById(uint256 _farmingId) external view returns (FarmRecord memory) { return farming[_farmingId]; } function getCommonAmuletPrices(uint256 _timestamp) external view returns (uint256[3] memory) { return _getCommonAmuletPrices(_timestamp); } function getOneAmuletPrice(address _token) external view returns (uint256) { return _getOneAmuletPrice(_token); } /////////////////////////////////////////////// /// Internals /////// /////////////////////////////////////////////// /** * @dev Save farming results in storage and mint * appropriate token (NFT, ERC20 or None) */ function _endFarming(uint256 _deployId, Result _res) internal { //TODO need refactor if EGGs will be FarmRecord storage f = farming[_deployId]; f.harvest = _res; // unstake creature ICreatures(farm.creatures).transferFrom(address(this), msg.sender, f.creatureId); eggs.burn(_deployId); // Burn EGG if (_res == Result.Fail) { //unstake land (if staked) if (ILand(farm.land).ownerOf(f.landId) == address(this)){ ILand(farm.land).transferFrom(address(this), msg.sender, f.landId); } emit Harvest( _deployId, msg.sender, uint8(_res), 0, //baseChance 0, //bonus.amuletHold, 0, //bonus.amuletBullTrend, 0 //bonus.inventoryHold ); } } function _stakeOneTool(uint8 _itemId) internal { require(IInventory(farm.inventory).balanceOf(msg.sender, _itemId) >= 1, "You must own this tool for stake!" ); //Before stake we need two checks. //1. Removed //2. Cant`t stake one tool more than one item require(userStakedTools[msg.sender][_itemId] == 0, "Tool is already staked"); //stake IInventory(farm.inventory).safeTransferFrom( msg.sender, address(this), _itemId, 1, bytes('0') ); userStakedTools[msg.sender][_itemId] = block.timestamp; } function _unstakeOneTool(uint8 _itemId) internal { require(userStakedTools[msg.sender][_itemId] > 0, "This tool is not staked yet"); require(block.timestamp - userStakedTools[msg.sender][_itemId] >= getToolUnstakeDelay(), "Cant unstake earlier than a week" ); userStakedTools[msg.sender][_itemId] = 0; IInventory(farm.inventory).safeTransferFrom( address(this), msg.sender, _itemId, 1, bytes('0') ); } function _saveCommonAmuletPrices(uint256 _timestamp) internal { //Lets check if price NOT exist for this timestamp - lets save it if (commonAmuletPrices[_timestamp][0] == 0) { for (uint8 i=0; i < COMMON_AMULETS.length; i++){ commonAmuletPrices[_timestamp][i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } } } function _checkAndSaveMaxAmuletPrice(address _amulet) internal { if (IERC20(_amulet).balanceOf(msg.sender) > maxAmuletBalances[_amulet] ) { maxAmuletBalances[_amulet] = IERC20(_amulet).balanceOf(msg.sender); } } function _getCommonAmuletPrices(uint256 _timestamp) internal view returns (uint256[3] memory) { //Lets check if price allready exist for this timestamp - just return it if (commonAmuletPrices[_timestamp][0] != 0) { return commonAmuletPrices[_timestamp]; } //If price is not exist lets get it from oracles uint256[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ res[i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } return res; } function _getCommonAmuletsHoldState(address _farmer) internal view returns (bool[3] memory) { //If token balance =0 - set false bool[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ if (IERC20(COMMON_AMULETS[i]).balanceOf(_farmer) > 0){ res[i] = true; } else { // Set to zero if token balance is 0 res[i] = false; } } return res; } function _getExistingAmuletsPrices(address[] memory _tokens) internal view returns (uint256[] memory) { uint256[] memory res = new uint256[](_tokens.length); for (uint8 i=0; i < _tokens.length; i++){ if (IERC20(_tokens[i]).balanceOf(msg.sender) > 0){ res[i] = _getOneAmuletPrice(_tokens[i]); } else { // Set to zero if token balance is 0 res[i] = 0; } } return res; } function _getOneAmuletPrice(address _token) internal view returns (uint256) { return IAmuletPriceProvider(priceProvider).getLastPrice(_token); } function _isRevelEnabled() internal view returns (bool) { return REVEAL_ENABLED; } function _reveal(uint randomSeed) internal { require ((landCount.left + allNormiesesLeft) > 0, "Sorry, no more reveal!"); //1. Lets choose Land OR Creature, % //So we have two possible results. 1 - Land, 0 - Creature. // sum of weights = 100, lets define weigth for Creature uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = uint8( uint32(allNormiesesLeft) * CREATURE_P_MULT // * 100 removed due CREATURE_P_MULT / (CREATURE_P_MULT * uint32(allNormiesesLeft) / 100 + uint32(landCount.left)) ); choiceWeight[1] = 100 - choiceWeight[0]; uint8 choice = uint8(_getWeightedChoice2(choiceWeight, randomSeed)); //Check that choice can be executed if (choice != 0 && landCount.left == 0) { //There are no more Lands. So we need change choice choice = 0; } if (choice == 0) { // create creature uint8[] memory choiceWeight0 = new uint8[](getCreatureTypeCount()); //2. Ok, Creature will be born. But what kind of? for (uint8 i = 0; i < getCreatureTypeCount(); i ++) { choiceWeight0[i] = uint8(creaturesBorn[i].leftNormie); } choice = uint8(_getWeightedChoice2(choiceWeight0, randomSeed / 0x10000)); // shift right 16 bits ICreatures(farm.creatures).mint( msg.sender, MAX_ALL_NORMIES - allNormiesesLeft, choice, //AnimalType 0, creaturesBorn[choice].totalNormie - creaturesBorn[choice].leftNormie + 1 // index ); emit Reveal(MAX_ALL_NORMIES - allNormiesesLeft, true, choice); allNormiesesLeft -= 1; creaturesBorn[choice].leftNormie -= 1; } else { // create land ILand(farm.land).mint( msg.sender, getMaxLands() - landCount.left ); emit Reveal(getMaxLands() - landCount.left , false, 0); landCount.left -= 1; } } function _getWeightedChoice2(uint8[] memory _weights, uint randomSeed) internal view returns (uint8){ uint256 sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { sum_of_weights += _weights[i]; } uint256 rnd = randomSeed % sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { if (rnd < _weights[i]) { return i; } rnd -= _weights[i]; } return 0; } /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); } /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)")); } function getCreatureTypeCount() virtual internal view returns (uint16); function getFarmingDuration() virtual internal view returns (uint); function getToolUnstakeDelay() virtual internal view returns (uint); function getNormieCountInType() virtual internal view returns (uint16); function getChadCountInType() virtual internal view returns (uint16); function getMaxLands() virtual internal view returns (uint16); function getUsersTokens(address _owner) external view returns (uint256[] memory) { return eggs.getUsersTokens(_owner); } }
farmDeploy
function farmDeploy(uint256 _creatureId, uint256 _landId) external { require(FARMING_ENABLED == true, "Chief Farmer not enable yet"); require(ICreatures(farm.creatures).ownerOf(_creatureId) == msg.sender, "Need to be Creature Owner" ); require(ILand(farm.land).ownerOf(_landId) == msg.sender, "Need to be Land Owner" ); (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity(_creatureId); require((DegenFarmBase.Rarity)(crRarity) == Rarity.Normie || (DegenFarmBase.Rarity)(crRarity) == Rarity.Chad, "Can farm only Normie and Chad"); //Check that farming available yet if (crRarity == 0) { require(creaturesBorn[crType].leftChadToDiscover > 0, "No more chads left"); } else { require(creaturesBorn[crType].leftDegenToDiscover > 0, "No more Degen left"); } //1. Lets make amulet price snapshot //1.1. First we need creat array with properly elements count uint256[] memory prices1 = new uint256[](amulets[crType].length); uint256[] memory prices2 = new uint256[](amulets[crType].length); prices1 = _getExistingAmuletsPrices(amulets[crType]); //2.Check and save Common Amulets price(if not exist yet) _saveCommonAmuletPrices(block.timestamp); //3. Save deploy record farming.push( FarmRecord({ creatureId: _creatureId, landId: _landId, harvestTime: block.timestamp + getFarmingDuration(), amuletsPrice1: prices1, amuletsPrice2: prices2, harvest: Result.Fail, harvestId: 0, commonAmuletInitialHold: _getCommonAmuletsHoldState(msg.sender) //save initial hold state }) ); // Let's mint Egg. eggs.mint( msg.sender, // farmer farming.length - 1 // tokenId ); //STAKE LAND and Creatures!!!! ILand(farm.land).transferFrom(msg.sender, address(this), _landId); ICreatures(farm.creatures).transferFrom(msg.sender, address(this), _creatureId); }
/** * @dev Start farming process. New NFT - Egg will minted for user * @param _creatureId - NFT tokenId, caller must be owner of this token * @param _landId -- NFT tokenId, caller must be owner of this token */
NatSpecMultiLine
v0.7.4+commit.3f05b770
MIT
ipfs://308c7d0f38216f626771d86f2b5b3091893bd5f12659a801a1f13db0060ec78f
{ "func_code_index": [ 6261, 8572 ] }
3,311
Creatures
DegensFarmBase.sol
0xd227df494367a8b769b4bf2bbebd0388a8758741
Solidity
DegenFarmBase
abstract contract DegenFarmBase is ERC1155Receiver, Ownable { enum AnimalType { Cow, Horse, Rabbit, Chicken, Pig, Cat, Dog, Goose, Goat, Sheep, Snake, Fish, Frog, Worm, Lama, Mouse, Camel, Donkey, Bee, Duck, GenesisEgg // 20 } enum Rarity { Normie, // 0 Chad, // 1 Degen, // 2 Unique // 3 } enum Result {Fail, Dung, Chad, Degen} //External conatrct addresses used with this farm. struct AddressRegistry { address land; address creatures; address inventory; address bagstoken; address dungtoken; } //Degens Farm Key numbers struct CreaturesCount { uint16 totalNormie; uint16 leftNormie; uint16 totalChad; uint16 leftChadToDiscover; uint16 totalDegen; uint16 leftDegenToDiscover; uint16 leftChadFarmAttempts; uint16 leftDegenFarmAttempts; } //Land count record struct LandCount { uint16 total; uint16 left; } // Record represent one farming act struct FarmRecord { uint256 creatureId; uint256 landId; uint256 harvestTime; uint256[] amuletsPrice1; uint256[] amuletsPrice2; Result harvest; uint256 harvestId; //new NFT tokenId bool[3] commonAmuletInitialHold; } // Bonus for better harvest struct Bonus { uint16 amuletHold; uint16 amuletBullTrend; uint16 inventoryHold; } uint8 constant public CREATURE_TYPE_COUNT_MAX = 20; //how much creatures types may be used //Creature probubility multiplier, scaled with 100. 3.00 - 300, 3.05 - 305 etc // so we need additional divide on 100 in formula uint32 constant public CREATURE_P_MULT = 230; uint16 public MAX_ALL_NORMIES = getCreatureTypeCount() * getNormieCountInType(); //subj uint256 constant public NFT_ID_MULTIPLIER = 10000; //must be set more then all Normies count uint256 constant public FARM_DUNG_AMOUNT = 250e32; //per one harvest uint16 constant public BONUS_POINTS_AMULET_HOLD = 10; uint16 constant public BONUS_POINTS_AMULET_BULL_TREND = 90; //Common Amulet addresses address[3] public COMMON_AMULETS = [ 0xa0246c9032bC3A600820415aE600c6388619A14D, 0x87d73E916D7057945c9BcD8cdd94e42A6F47f776, 0x126c121f99e1E211dF2e5f8De2d96Fa36647c855 ]; bool public REVEAL_ENABLED = false; bool public FARMING_ENABLED = false; address public priceProvider; IEggs public eggs; address[][CREATURE_TYPE_COUNT_MAX] public amulets; //amulets for creatures AddressRegistry public farm; LandCount public landCount; //common token price snapshots mapping(uint256 => uint256[3]) public commonAmuletPrices; mapping(address => uint256) public maxAmuletBalances; // mapping from user to his(her) staked tools // Index of uint256[6] represent tool NFT itemID mapping(address => uint256[6]) public userStakedTools; uint16 public allNormiesesLeft; CreaturesCount[CREATURE_TYPE_COUNT_MAX] public creaturesBorn; FarmRecord[] farming; event Reveal(uint256 indexed _tokenId, bool _isCreature, uint8 _animalType); event Harvest( uint256 indexed _eggId, address farmer, uint8 result , uint16 baseChance, uint16 amuletHold, uint16 amuletBullTrend, uint16 inventoryHold ); constructor ( address _land, address _creatures, address _inventory, address _bagstoken, address _dungtoken, IEggs _eggs ) { farm.land = _land; farm.creatures = _creatures; farm.inventory = _inventory; farm.bagstoken = _bagstoken; farm.dungtoken = _dungtoken; // Index of creaturesBorn in this initial setting // must NOT exceed CREATURE_TYPE_COUNT for (uint i = 0; i < getCreatureTypeCount(); i++) { creaturesBorn[i] = CreaturesCount( getNormieCountInType(), // totalNormie; getNormieCountInType(), // leftNormie; getChadCountInType(), // totalChad; getChadCountInType(), // leftChadToDiscover; 1, // totalDegen; 1, // leftDegenToDiscover; getNormieCountInType(), // leftChadFarmAttempts; getChadCountInType()); // leftDegenFarmAttempts; } landCount = LandCount(getMaxLands(), getMaxLands()); allNormiesesLeft = MAX_ALL_NORMIES; eggs = _eggs; } /** * @dev Changes inventory contract */ function setInventory(address _inventory) external onlyOwner { farm.inventory = _inventory; } function reveal(uint count) external { require(_isRevelEnabled(), "Please wait for reveal enabled."); require(count > 0, "Count must be positive"); require(count <= 8, "Count must less than 9"); // random limit require( IERC20(farm.bagstoken).allowance(msg.sender, address(this)) >= count*1, "Please approve your BAGS token to this contract." ); require( IERC20(farm.bagstoken).transferFrom(msg.sender, address(this), count*1) ); uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); // random seed for 8 reveals (8x32=256) for (uint i = 0; i < count; i++) { _reveal(randomSeed); randomSeed = randomSeed / 0x100000000; // shift right 32 bits } } event Log(string mess); /** * @dev Start farming process. New NFT - Egg will minted for user * @param _creatureId - NFT tokenId, caller must be owner of this token * @param _landId -- NFT tokenId, caller must be owner of this token */ function farmDeploy(uint256 _creatureId, uint256 _landId) external { require(FARMING_ENABLED == true, "Chief Farmer not enable yet"); require(ICreatures(farm.creatures).ownerOf(_creatureId) == msg.sender, "Need to be Creature Owner" ); require(ILand(farm.land).ownerOf(_landId) == msg.sender, "Need to be Land Owner" ); (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity(_creatureId); require((DegenFarmBase.Rarity)(crRarity) == Rarity.Normie || (DegenFarmBase.Rarity)(crRarity) == Rarity.Chad, "Can farm only Normie and Chad"); //Check that farming available yet if (crRarity == 0) { require(creaturesBorn[crType].leftChadToDiscover > 0, "No more chads left"); } else { require(creaturesBorn[crType].leftDegenToDiscover > 0, "No more Degen left"); } //1. Lets make amulet price snapshot //1.1. First we need creat array with properly elements count uint256[] memory prices1 = new uint256[](amulets[crType].length); uint256[] memory prices2 = new uint256[](amulets[crType].length); prices1 = _getExistingAmuletsPrices(amulets[crType]); //2.Check and save Common Amulets price(if not exist yet) _saveCommonAmuletPrices(block.timestamp); //3. Save deploy record farming.push( FarmRecord({ creatureId: _creatureId, landId: _landId, harvestTime: block.timestamp + getFarmingDuration(), amuletsPrice1: prices1, amuletsPrice2: prices2, harvest: Result.Fail, harvestId: 0, commonAmuletInitialHold: _getCommonAmuletsHoldState(msg.sender) //save initial hold state }) ); // Let's mint Egg. eggs.mint( msg.sender, // farmer farming.length - 1 // tokenId ); //STAKE LAND and Creatures!!!! ILand(farm.land).transferFrom(msg.sender, address(this), _landId); ICreatures(farm.creatures).transferFrom(msg.sender, address(this), _creatureId); } /** * @dev Finish farming process. Egg NFT will be burn * @param _deployId - NFT tokenId, caller must be owner of this token */ function harvest(uint256 _deployId) external { require(eggs.ownerOf(_deployId) == msg.sender, "This is NOT YOUR EGG"); FarmRecord storage f = farming[_deployId]; require(f.harvestTime <= block.timestamp, "To early for harvest"); //Lets Calculate Dung/CHAD-DEGEN chance Result farmingResult; Bonus memory bonus; //1. BaseChance (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity( f.creatureId ); uint16 baseChance; if (crRarity == 0) { //Try farm CHAD. So if there is no CHADs any more we must return assets if (creaturesBorn[crType].leftChadToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftChadToDiscover * 100 /(creaturesBorn[crType].leftChadFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftChadFarmAttempts -= 1; } else { //Try farm DEGEN. So if there is no DEGENSs any more we must return assets if (creaturesBorn[crType].leftDegenToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftDegenToDiscover * 100 /(creaturesBorn[crType].leftDegenFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftDegenFarmAttempts -= 1; } ////////////////////////////////////////////// // 2. Bonus for amulet token ***HOLD*** // 3. Bonus for amulets BULLs trend ////////////////////////////////////////////// bonus.amuletHold = 0; bonus.amuletBullTrend = 0; //Check common amulets _saveCommonAmuletPrices(block.timestamp); //Get current hold stae for (uint8 i = 0; i < COMMON_AMULETS.length; i ++){ if (f.commonAmuletInitialHold[i] && _getCommonAmuletsHoldState(msg.sender)[i]) { //token was hold at deploy time and now - iT IS GOOD //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(COMMON_AMULETS[i]); bonus.amuletHold = uint16( IERC20(COMMON_AMULETS[i]).balanceOf(msg.sender) * 100 / maxAmuletBalances[COMMON_AMULETS[i]] * BONUS_POINTS_AMULET_HOLD / 100 //100 used for scale ); //Lets check Bull TREND if (_getCommonAmuletPrices(f.harvestTime - getFarmingDuration())[i] < _getCommonAmuletPrices(block.timestamp)[i] ) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } //Ok, if there is NO common amulets lets check personal uint256[] memory prices2 = new uint256[](amulets[crType].length); prices2 = _getExistingAmuletsPrices(amulets[crType]); if (bonus.amuletHold != BONUS_POINTS_AMULET_HOLD) { for (uint8 i=0; i < f.amuletsPrice1.length; i ++){ if (f.amuletsPrice1[i] > 0 && prices2[i] > 0){ //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(amulets[i][crType]); bonus.amuletHold = uint16( IERC20(amulets[i][crType]).balanceOf(msg.sender) * 100 //100 used for scale / maxAmuletBalances[amulets[i][crType]] * BONUS_POINTS_AMULET_HOLD /100 ); //Lets check Bull TREND if (f.amuletsPrice1[i] < prices2[i]) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } } ////////////////////////////////////////////// ////////////////////////////////////////////// //4. Bonus for inventory ////////////////////////////////////////////// bonus.inventoryHold = 0; if (userStakedTools[msg.sender].length > 0) { for (uint8 i=0; i<userStakedTools[msg.sender].length; i++) { if (userStakedTools[msg.sender][i] > 0){ bonus.inventoryHold = bonus.inventoryHold + IInventory(farm.inventory).getToolBoost(i); } } } ////////////////////////////////////////////// uint16 allBonus = bonus.amuletHold + bonus.amuletBullTrend + bonus.inventoryHold; uint8 chanceOfRarityUP = uint8( (baseChance + allBonus) * 100 / (100 + allBonus) ); uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = chanceOfRarityUP; choiceWeight[1] = 100 - chanceOfRarityUP; uint8 choice = uint8(_getWeightedChoice(choiceWeight)); if (choice == 0) { f.harvestId = (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId; // Mint new chad/degen uint32 index; //Decrease appropriate CREATRURE COUNT if (crRarity + 1 == uint8(Rarity.Chad)) { index = creaturesBorn[crType].totalChad - creaturesBorn[crType].leftChadToDiscover + 1; creaturesBorn[crType].leftChadToDiscover -= 1; farmingResult = Result.Chad; } else if (crRarity + 1 == uint8(Rarity.Degen)) { index = creaturesBorn[crType].totalDegen - creaturesBorn[crType].leftDegenToDiscover + 1; creaturesBorn[crType].leftDegenToDiscover -= 1; farmingResult = Result.Degen; } ICreatures(farm.creatures).mint( msg.sender, (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId, // new iD crType, //AnimalType crRarity + 1, index // index ); } else { //Mint new dung IDung(farm.dungtoken).mint(msg.sender, FARM_DUNG_AMOUNT); farmingResult = Result.Dung; } //BURN Land ILand(farm.land).burn(f.landId); _endFarming(_deployId, farmingResult); emit Harvest( _deployId, msg.sender, uint8(farmingResult), baseChance, bonus.amuletHold, bonus.amuletBullTrend, bonus.inventoryHold ); } /** * @dev Stake one inventory item * @param _itemId - NFT tokenId, caller must be owner of this token */ function stakeOneTool(uint8 _itemId) external { _stakeOneTool(_itemId); } /** * @dev UnStake one inventory item * @param _itemId - NFT tokenId */ function unstakeOneTool(uint8 _itemId) external { _unstakeOneTool(_itemId); } ///////////////////////////////////////////////////// //// Admin functions /////// ///////////////////////////////////////////////////// function setOneCommonAmulet(uint8 _index, address _token) external onlyOwner { COMMON_AMULETS[_index] = _token; } function setAmuletForOneCreature(uint8 _index, address[] memory _tokens) external onlyOwner { delete amulets[_index]; amulets[_index] = _tokens; } function setPriceProvider(address _priceProvider) external onlyOwner { priceProvider = _priceProvider; } function enableReveal(bool _isEnabled) external onlyOwner { REVEAL_ENABLED = _isEnabled; } function enableFarming(bool _isEnabled) external onlyOwner { FARMING_ENABLED = _isEnabled; } //////////////////////////////////////// /// Proxy for NFT Operators mamnage // //////////////////////////////////////// function addOperator(address _contract, address newOperator) external onlyOwner { IOperatorManage(_contract).addOperator(newOperator); } function removeOperator(address _contract, address oldOperator) external onlyOwner { IOperatorManage(_contract).removeOperator(oldOperator); } function reclaimToken(address _contract, IERC20 anyTokens, address _admin) external onlyOwner { IOperatorManage(_contract).withdrawERC20(anyTokens, _admin); } //////////////////////////////////////////////////////// function getCreatureAmulets(uint8 _creatureType) external view returns (address[] memory) { return _getCreatureAmulets(_creatureType); } function _getCreatureAmulets(uint8 _creatureType) internal view returns (address[] memory) { return amulets[_creatureType]; } function getCreatureStat(uint8 _creatureType) external view returns ( uint16, uint16, uint16, uint16, uint16, uint16, uint16, uint16 ) { CreaturesCount storage stat = creaturesBorn[_creatureType]; return ( stat.totalNormie, stat.leftNormie, stat.totalChad, stat.leftChadToDiscover, stat.totalDegen, stat.leftDegenToDiscover, stat.leftChadFarmAttempts, stat.leftDegenFarmAttempts ); } function getWeightedChoice(uint8[] memory _weights) external view returns (uint8){ return _getWeightedChoice(_weights); } function _getWeightedChoice(uint8[] memory _weights) internal view returns (uint8){ uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); return _getWeightedChoice2(_weights, randomSeed); } function getFarmingById(uint256 _farmingId) external view returns (FarmRecord memory) { return farming[_farmingId]; } function getCommonAmuletPrices(uint256 _timestamp) external view returns (uint256[3] memory) { return _getCommonAmuletPrices(_timestamp); } function getOneAmuletPrice(address _token) external view returns (uint256) { return _getOneAmuletPrice(_token); } /////////////////////////////////////////////// /// Internals /////// /////////////////////////////////////////////// /** * @dev Save farming results in storage and mint * appropriate token (NFT, ERC20 or None) */ function _endFarming(uint256 _deployId, Result _res) internal { //TODO need refactor if EGGs will be FarmRecord storage f = farming[_deployId]; f.harvest = _res; // unstake creature ICreatures(farm.creatures).transferFrom(address(this), msg.sender, f.creatureId); eggs.burn(_deployId); // Burn EGG if (_res == Result.Fail) { //unstake land (if staked) if (ILand(farm.land).ownerOf(f.landId) == address(this)){ ILand(farm.land).transferFrom(address(this), msg.sender, f.landId); } emit Harvest( _deployId, msg.sender, uint8(_res), 0, //baseChance 0, //bonus.amuletHold, 0, //bonus.amuletBullTrend, 0 //bonus.inventoryHold ); } } function _stakeOneTool(uint8 _itemId) internal { require(IInventory(farm.inventory).balanceOf(msg.sender, _itemId) >= 1, "You must own this tool for stake!" ); //Before stake we need two checks. //1. Removed //2. Cant`t stake one tool more than one item require(userStakedTools[msg.sender][_itemId] == 0, "Tool is already staked"); //stake IInventory(farm.inventory).safeTransferFrom( msg.sender, address(this), _itemId, 1, bytes('0') ); userStakedTools[msg.sender][_itemId] = block.timestamp; } function _unstakeOneTool(uint8 _itemId) internal { require(userStakedTools[msg.sender][_itemId] > 0, "This tool is not staked yet"); require(block.timestamp - userStakedTools[msg.sender][_itemId] >= getToolUnstakeDelay(), "Cant unstake earlier than a week" ); userStakedTools[msg.sender][_itemId] = 0; IInventory(farm.inventory).safeTransferFrom( address(this), msg.sender, _itemId, 1, bytes('0') ); } function _saveCommonAmuletPrices(uint256 _timestamp) internal { //Lets check if price NOT exist for this timestamp - lets save it if (commonAmuletPrices[_timestamp][0] == 0) { for (uint8 i=0; i < COMMON_AMULETS.length; i++){ commonAmuletPrices[_timestamp][i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } } } function _checkAndSaveMaxAmuletPrice(address _amulet) internal { if (IERC20(_amulet).balanceOf(msg.sender) > maxAmuletBalances[_amulet] ) { maxAmuletBalances[_amulet] = IERC20(_amulet).balanceOf(msg.sender); } } function _getCommonAmuletPrices(uint256 _timestamp) internal view returns (uint256[3] memory) { //Lets check if price allready exist for this timestamp - just return it if (commonAmuletPrices[_timestamp][0] != 0) { return commonAmuletPrices[_timestamp]; } //If price is not exist lets get it from oracles uint256[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ res[i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } return res; } function _getCommonAmuletsHoldState(address _farmer) internal view returns (bool[3] memory) { //If token balance =0 - set false bool[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ if (IERC20(COMMON_AMULETS[i]).balanceOf(_farmer) > 0){ res[i] = true; } else { // Set to zero if token balance is 0 res[i] = false; } } return res; } function _getExistingAmuletsPrices(address[] memory _tokens) internal view returns (uint256[] memory) { uint256[] memory res = new uint256[](_tokens.length); for (uint8 i=0; i < _tokens.length; i++){ if (IERC20(_tokens[i]).balanceOf(msg.sender) > 0){ res[i] = _getOneAmuletPrice(_tokens[i]); } else { // Set to zero if token balance is 0 res[i] = 0; } } return res; } function _getOneAmuletPrice(address _token) internal view returns (uint256) { return IAmuletPriceProvider(priceProvider).getLastPrice(_token); } function _isRevelEnabled() internal view returns (bool) { return REVEAL_ENABLED; } function _reveal(uint randomSeed) internal { require ((landCount.left + allNormiesesLeft) > 0, "Sorry, no more reveal!"); //1. Lets choose Land OR Creature, % //So we have two possible results. 1 - Land, 0 - Creature. // sum of weights = 100, lets define weigth for Creature uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = uint8( uint32(allNormiesesLeft) * CREATURE_P_MULT // * 100 removed due CREATURE_P_MULT / (CREATURE_P_MULT * uint32(allNormiesesLeft) / 100 + uint32(landCount.left)) ); choiceWeight[1] = 100 - choiceWeight[0]; uint8 choice = uint8(_getWeightedChoice2(choiceWeight, randomSeed)); //Check that choice can be executed if (choice != 0 && landCount.left == 0) { //There are no more Lands. So we need change choice choice = 0; } if (choice == 0) { // create creature uint8[] memory choiceWeight0 = new uint8[](getCreatureTypeCount()); //2. Ok, Creature will be born. But what kind of? for (uint8 i = 0; i < getCreatureTypeCount(); i ++) { choiceWeight0[i] = uint8(creaturesBorn[i].leftNormie); } choice = uint8(_getWeightedChoice2(choiceWeight0, randomSeed / 0x10000)); // shift right 16 bits ICreatures(farm.creatures).mint( msg.sender, MAX_ALL_NORMIES - allNormiesesLeft, choice, //AnimalType 0, creaturesBorn[choice].totalNormie - creaturesBorn[choice].leftNormie + 1 // index ); emit Reveal(MAX_ALL_NORMIES - allNormiesesLeft, true, choice); allNormiesesLeft -= 1; creaturesBorn[choice].leftNormie -= 1; } else { // create land ILand(farm.land).mint( msg.sender, getMaxLands() - landCount.left ); emit Reveal(getMaxLands() - landCount.left , false, 0); landCount.left -= 1; } } function _getWeightedChoice2(uint8[] memory _weights, uint randomSeed) internal view returns (uint8){ uint256 sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { sum_of_weights += _weights[i]; } uint256 rnd = randomSeed % sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { if (rnd < _weights[i]) { return i; } rnd -= _weights[i]; } return 0; } /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); } /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)")); } function getCreatureTypeCount() virtual internal view returns (uint16); function getFarmingDuration() virtual internal view returns (uint); function getToolUnstakeDelay() virtual internal view returns (uint); function getNormieCountInType() virtual internal view returns (uint16); function getChadCountInType() virtual internal view returns (uint16); function getMaxLands() virtual internal view returns (uint16); function getUsersTokens(address _owner) external view returns (uint256[] memory) { return eggs.getUsersTokens(_owner); } }
harvest
function harvest(uint256 _deployId) external { require(eggs.ownerOf(_deployId) == msg.sender, "This is NOT YOUR EGG"); FarmRecord storage f = farming[_deployId]; require(f.harvestTime <= block.timestamp, "To early for harvest"); //Lets Calculate Dung/CHAD-DEGEN chance Result farmingResult; Bonus memory bonus; //1. BaseChance (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity( f.creatureId ); uint16 baseChance; if (crRarity == 0) { //Try farm CHAD. So if there is no CHADs any more we must return assets if (creaturesBorn[crType].leftChadToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftChadToDiscover * 100 /(creaturesBorn[crType].leftChadFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftChadFarmAttempts -= 1; } else { //Try farm DEGEN. So if there is no DEGENSs any more we must return assets if (creaturesBorn[crType].leftDegenToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftDegenToDiscover * 100 /(creaturesBorn[crType].leftDegenFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftDegenFarmAttempts -= 1; } ////////////////////////////////////////////// // 2. Bonus for amulet token ***HOLD*** // 3. Bonus for amulets BULLs trend ////////////////////////////////////////////// bonus.amuletHold = 0; bonus.amuletBullTrend = 0; //Check common amulets _saveCommonAmuletPrices(block.timestamp); //Get current hold stae for (uint8 i = 0; i < COMMON_AMULETS.length; i ++){ if (f.commonAmuletInitialHold[i] && _getCommonAmuletsHoldState(msg.sender)[i]) { //token was hold at deploy time and now - iT IS GOOD //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(COMMON_AMULETS[i]); bonus.amuletHold = uint16( IERC20(COMMON_AMULETS[i]).balanceOf(msg.sender) * 100 / maxAmuletBalances[COMMON_AMULETS[i]] * BONUS_POINTS_AMULET_HOLD / 100 //100 used for scale ); //Lets check Bull TREND if (_getCommonAmuletPrices(f.harvestTime - getFarmingDuration())[i] < _getCommonAmuletPrices(block.timestamp)[i] ) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } //Ok, if there is NO common amulets lets check personal uint256[] memory prices2 = new uint256[](amulets[crType].length); prices2 = _getExistingAmuletsPrices(amulets[crType]); if (bonus.amuletHold != BONUS_POINTS_AMULET_HOLD) { for (uint8 i=0; i < f.amuletsPrice1.length; i ++){ if (f.amuletsPrice1[i] > 0 && prices2[i] > 0){ //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(amulets[i][crType]); bonus.amuletHold = uint16( IERC20(amulets[i][crType]).balanceOf(msg.sender) * 100 //100 used for scale / maxAmuletBalances[amulets[i][crType]] * BONUS_POINTS_AMULET_HOLD /100 ); //Lets check Bull TREND if (f.amuletsPrice1[i] < prices2[i]) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } } ////////////////////////////////////////////// ////////////////////////////////////////////// //4. Bonus for inventory ////////////////////////////////////////////// bonus.inventoryHold = 0; if (userStakedTools[msg.sender].length > 0) { for (uint8 i=0; i<userStakedTools[msg.sender].length; i++) { if (userStakedTools[msg.sender][i] > 0){ bonus.inventoryHold = bonus.inventoryHold + IInventory(farm.inventory).getToolBoost(i); } } } ////////////////////////////////////////////// uint16 allBonus = bonus.amuletHold + bonus.amuletBullTrend + bonus.inventoryHold; uint8 chanceOfRarityUP = uint8( (baseChance + allBonus) * 100 / (100 + allBonus) ); uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = chanceOfRarityUP; choiceWeight[1] = 100 - chanceOfRarityUP; uint8 choice = uint8(_getWeightedChoice(choiceWeight)); if (choice == 0) { f.harvestId = (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId; // Mint new chad/degen uint32 index; //Decrease appropriate CREATRURE COUNT if (crRarity + 1 == uint8(Rarity.Chad)) { index = creaturesBorn[crType].totalChad - creaturesBorn[crType].leftChadToDiscover + 1; creaturesBorn[crType].leftChadToDiscover -= 1; farmingResult = Result.Chad; } else if (crRarity + 1 == uint8(Rarity.Degen)) { index = creaturesBorn[crType].totalDegen - creaturesBorn[crType].leftDegenToDiscover + 1; creaturesBorn[crType].leftDegenToDiscover -= 1; farmingResult = Result.Degen; } ICreatures(farm.creatures).mint( msg.sender, (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId, // new iD crType, //AnimalType crRarity + 1, index // index ); } else { //Mint new dung IDung(farm.dungtoken).mint(msg.sender, FARM_DUNG_AMOUNT); farmingResult = Result.Dung; } //BURN Land ILand(farm.land).burn(f.landId); _endFarming(_deployId, farmingResult); emit Harvest( _deployId, msg.sender, uint8(farmingResult), baseChance, bonus.amuletHold, bonus.amuletBullTrend, bonus.inventoryHold ); }
/** * @dev Finish farming process. Egg NFT will be burn * @param _deployId - NFT tokenId, caller must be owner of this token */
NatSpecMultiLine
v0.7.4+commit.3f05b770
MIT
ipfs://308c7d0f38216f626771d86f2b5b3091893bd5f12659a801a1f13db0060ec78f
{ "func_code_index": [ 8728, 15754 ] }
3,312
Creatures
DegensFarmBase.sol
0xd227df494367a8b769b4bf2bbebd0388a8758741
Solidity
DegenFarmBase
abstract contract DegenFarmBase is ERC1155Receiver, Ownable { enum AnimalType { Cow, Horse, Rabbit, Chicken, Pig, Cat, Dog, Goose, Goat, Sheep, Snake, Fish, Frog, Worm, Lama, Mouse, Camel, Donkey, Bee, Duck, GenesisEgg // 20 } enum Rarity { Normie, // 0 Chad, // 1 Degen, // 2 Unique // 3 } enum Result {Fail, Dung, Chad, Degen} //External conatrct addresses used with this farm. struct AddressRegistry { address land; address creatures; address inventory; address bagstoken; address dungtoken; } //Degens Farm Key numbers struct CreaturesCount { uint16 totalNormie; uint16 leftNormie; uint16 totalChad; uint16 leftChadToDiscover; uint16 totalDegen; uint16 leftDegenToDiscover; uint16 leftChadFarmAttempts; uint16 leftDegenFarmAttempts; } //Land count record struct LandCount { uint16 total; uint16 left; } // Record represent one farming act struct FarmRecord { uint256 creatureId; uint256 landId; uint256 harvestTime; uint256[] amuletsPrice1; uint256[] amuletsPrice2; Result harvest; uint256 harvestId; //new NFT tokenId bool[3] commonAmuletInitialHold; } // Bonus for better harvest struct Bonus { uint16 amuletHold; uint16 amuletBullTrend; uint16 inventoryHold; } uint8 constant public CREATURE_TYPE_COUNT_MAX = 20; //how much creatures types may be used //Creature probubility multiplier, scaled with 100. 3.00 - 300, 3.05 - 305 etc // so we need additional divide on 100 in formula uint32 constant public CREATURE_P_MULT = 230; uint16 public MAX_ALL_NORMIES = getCreatureTypeCount() * getNormieCountInType(); //subj uint256 constant public NFT_ID_MULTIPLIER = 10000; //must be set more then all Normies count uint256 constant public FARM_DUNG_AMOUNT = 250e32; //per one harvest uint16 constant public BONUS_POINTS_AMULET_HOLD = 10; uint16 constant public BONUS_POINTS_AMULET_BULL_TREND = 90; //Common Amulet addresses address[3] public COMMON_AMULETS = [ 0xa0246c9032bC3A600820415aE600c6388619A14D, 0x87d73E916D7057945c9BcD8cdd94e42A6F47f776, 0x126c121f99e1E211dF2e5f8De2d96Fa36647c855 ]; bool public REVEAL_ENABLED = false; bool public FARMING_ENABLED = false; address public priceProvider; IEggs public eggs; address[][CREATURE_TYPE_COUNT_MAX] public amulets; //amulets for creatures AddressRegistry public farm; LandCount public landCount; //common token price snapshots mapping(uint256 => uint256[3]) public commonAmuletPrices; mapping(address => uint256) public maxAmuletBalances; // mapping from user to his(her) staked tools // Index of uint256[6] represent tool NFT itemID mapping(address => uint256[6]) public userStakedTools; uint16 public allNormiesesLeft; CreaturesCount[CREATURE_TYPE_COUNT_MAX] public creaturesBorn; FarmRecord[] farming; event Reveal(uint256 indexed _tokenId, bool _isCreature, uint8 _animalType); event Harvest( uint256 indexed _eggId, address farmer, uint8 result , uint16 baseChance, uint16 amuletHold, uint16 amuletBullTrend, uint16 inventoryHold ); constructor ( address _land, address _creatures, address _inventory, address _bagstoken, address _dungtoken, IEggs _eggs ) { farm.land = _land; farm.creatures = _creatures; farm.inventory = _inventory; farm.bagstoken = _bagstoken; farm.dungtoken = _dungtoken; // Index of creaturesBorn in this initial setting // must NOT exceed CREATURE_TYPE_COUNT for (uint i = 0; i < getCreatureTypeCount(); i++) { creaturesBorn[i] = CreaturesCount( getNormieCountInType(), // totalNormie; getNormieCountInType(), // leftNormie; getChadCountInType(), // totalChad; getChadCountInType(), // leftChadToDiscover; 1, // totalDegen; 1, // leftDegenToDiscover; getNormieCountInType(), // leftChadFarmAttempts; getChadCountInType()); // leftDegenFarmAttempts; } landCount = LandCount(getMaxLands(), getMaxLands()); allNormiesesLeft = MAX_ALL_NORMIES; eggs = _eggs; } /** * @dev Changes inventory contract */ function setInventory(address _inventory) external onlyOwner { farm.inventory = _inventory; } function reveal(uint count) external { require(_isRevelEnabled(), "Please wait for reveal enabled."); require(count > 0, "Count must be positive"); require(count <= 8, "Count must less than 9"); // random limit require( IERC20(farm.bagstoken).allowance(msg.sender, address(this)) >= count*1, "Please approve your BAGS token to this contract." ); require( IERC20(farm.bagstoken).transferFrom(msg.sender, address(this), count*1) ); uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); // random seed for 8 reveals (8x32=256) for (uint i = 0; i < count; i++) { _reveal(randomSeed); randomSeed = randomSeed / 0x100000000; // shift right 32 bits } } event Log(string mess); /** * @dev Start farming process. New NFT - Egg will minted for user * @param _creatureId - NFT tokenId, caller must be owner of this token * @param _landId -- NFT tokenId, caller must be owner of this token */ function farmDeploy(uint256 _creatureId, uint256 _landId) external { require(FARMING_ENABLED == true, "Chief Farmer not enable yet"); require(ICreatures(farm.creatures).ownerOf(_creatureId) == msg.sender, "Need to be Creature Owner" ); require(ILand(farm.land).ownerOf(_landId) == msg.sender, "Need to be Land Owner" ); (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity(_creatureId); require((DegenFarmBase.Rarity)(crRarity) == Rarity.Normie || (DegenFarmBase.Rarity)(crRarity) == Rarity.Chad, "Can farm only Normie and Chad"); //Check that farming available yet if (crRarity == 0) { require(creaturesBorn[crType].leftChadToDiscover > 0, "No more chads left"); } else { require(creaturesBorn[crType].leftDegenToDiscover > 0, "No more Degen left"); } //1. Lets make amulet price snapshot //1.1. First we need creat array with properly elements count uint256[] memory prices1 = new uint256[](amulets[crType].length); uint256[] memory prices2 = new uint256[](amulets[crType].length); prices1 = _getExistingAmuletsPrices(amulets[crType]); //2.Check and save Common Amulets price(if not exist yet) _saveCommonAmuletPrices(block.timestamp); //3. Save deploy record farming.push( FarmRecord({ creatureId: _creatureId, landId: _landId, harvestTime: block.timestamp + getFarmingDuration(), amuletsPrice1: prices1, amuletsPrice2: prices2, harvest: Result.Fail, harvestId: 0, commonAmuletInitialHold: _getCommonAmuletsHoldState(msg.sender) //save initial hold state }) ); // Let's mint Egg. eggs.mint( msg.sender, // farmer farming.length - 1 // tokenId ); //STAKE LAND and Creatures!!!! ILand(farm.land).transferFrom(msg.sender, address(this), _landId); ICreatures(farm.creatures).transferFrom(msg.sender, address(this), _creatureId); } /** * @dev Finish farming process. Egg NFT will be burn * @param _deployId - NFT tokenId, caller must be owner of this token */ function harvest(uint256 _deployId) external { require(eggs.ownerOf(_deployId) == msg.sender, "This is NOT YOUR EGG"); FarmRecord storage f = farming[_deployId]; require(f.harvestTime <= block.timestamp, "To early for harvest"); //Lets Calculate Dung/CHAD-DEGEN chance Result farmingResult; Bonus memory bonus; //1. BaseChance (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity( f.creatureId ); uint16 baseChance; if (crRarity == 0) { //Try farm CHAD. So if there is no CHADs any more we must return assets if (creaturesBorn[crType].leftChadToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftChadToDiscover * 100 /(creaturesBorn[crType].leftChadFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftChadFarmAttempts -= 1; } else { //Try farm DEGEN. So if there is no DEGENSs any more we must return assets if (creaturesBorn[crType].leftDegenToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftDegenToDiscover * 100 /(creaturesBorn[crType].leftDegenFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftDegenFarmAttempts -= 1; } ////////////////////////////////////////////// // 2. Bonus for amulet token ***HOLD*** // 3. Bonus for amulets BULLs trend ////////////////////////////////////////////// bonus.amuletHold = 0; bonus.amuletBullTrend = 0; //Check common amulets _saveCommonAmuletPrices(block.timestamp); //Get current hold stae for (uint8 i = 0; i < COMMON_AMULETS.length; i ++){ if (f.commonAmuletInitialHold[i] && _getCommonAmuletsHoldState(msg.sender)[i]) { //token was hold at deploy time and now - iT IS GOOD //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(COMMON_AMULETS[i]); bonus.amuletHold = uint16( IERC20(COMMON_AMULETS[i]).balanceOf(msg.sender) * 100 / maxAmuletBalances[COMMON_AMULETS[i]] * BONUS_POINTS_AMULET_HOLD / 100 //100 used for scale ); //Lets check Bull TREND if (_getCommonAmuletPrices(f.harvestTime - getFarmingDuration())[i] < _getCommonAmuletPrices(block.timestamp)[i] ) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } //Ok, if there is NO common amulets lets check personal uint256[] memory prices2 = new uint256[](amulets[crType].length); prices2 = _getExistingAmuletsPrices(amulets[crType]); if (bonus.amuletHold != BONUS_POINTS_AMULET_HOLD) { for (uint8 i=0; i < f.amuletsPrice1.length; i ++){ if (f.amuletsPrice1[i] > 0 && prices2[i] > 0){ //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(amulets[i][crType]); bonus.amuletHold = uint16( IERC20(amulets[i][crType]).balanceOf(msg.sender) * 100 //100 used for scale / maxAmuletBalances[amulets[i][crType]] * BONUS_POINTS_AMULET_HOLD /100 ); //Lets check Bull TREND if (f.amuletsPrice1[i] < prices2[i]) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } } ////////////////////////////////////////////// ////////////////////////////////////////////// //4. Bonus for inventory ////////////////////////////////////////////// bonus.inventoryHold = 0; if (userStakedTools[msg.sender].length > 0) { for (uint8 i=0; i<userStakedTools[msg.sender].length; i++) { if (userStakedTools[msg.sender][i] > 0){ bonus.inventoryHold = bonus.inventoryHold + IInventory(farm.inventory).getToolBoost(i); } } } ////////////////////////////////////////////// uint16 allBonus = bonus.amuletHold + bonus.amuletBullTrend + bonus.inventoryHold; uint8 chanceOfRarityUP = uint8( (baseChance + allBonus) * 100 / (100 + allBonus) ); uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = chanceOfRarityUP; choiceWeight[1] = 100 - chanceOfRarityUP; uint8 choice = uint8(_getWeightedChoice(choiceWeight)); if (choice == 0) { f.harvestId = (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId; // Mint new chad/degen uint32 index; //Decrease appropriate CREATRURE COUNT if (crRarity + 1 == uint8(Rarity.Chad)) { index = creaturesBorn[crType].totalChad - creaturesBorn[crType].leftChadToDiscover + 1; creaturesBorn[crType].leftChadToDiscover -= 1; farmingResult = Result.Chad; } else if (crRarity + 1 == uint8(Rarity.Degen)) { index = creaturesBorn[crType].totalDegen - creaturesBorn[crType].leftDegenToDiscover + 1; creaturesBorn[crType].leftDegenToDiscover -= 1; farmingResult = Result.Degen; } ICreatures(farm.creatures).mint( msg.sender, (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId, // new iD crType, //AnimalType crRarity + 1, index // index ); } else { //Mint new dung IDung(farm.dungtoken).mint(msg.sender, FARM_DUNG_AMOUNT); farmingResult = Result.Dung; } //BURN Land ILand(farm.land).burn(f.landId); _endFarming(_deployId, farmingResult); emit Harvest( _deployId, msg.sender, uint8(farmingResult), baseChance, bonus.amuletHold, bonus.amuletBullTrend, bonus.inventoryHold ); } /** * @dev Stake one inventory item * @param _itemId - NFT tokenId, caller must be owner of this token */ function stakeOneTool(uint8 _itemId) external { _stakeOneTool(_itemId); } /** * @dev UnStake one inventory item * @param _itemId - NFT tokenId */ function unstakeOneTool(uint8 _itemId) external { _unstakeOneTool(_itemId); } ///////////////////////////////////////////////////// //// Admin functions /////// ///////////////////////////////////////////////////// function setOneCommonAmulet(uint8 _index, address _token) external onlyOwner { COMMON_AMULETS[_index] = _token; } function setAmuletForOneCreature(uint8 _index, address[] memory _tokens) external onlyOwner { delete amulets[_index]; amulets[_index] = _tokens; } function setPriceProvider(address _priceProvider) external onlyOwner { priceProvider = _priceProvider; } function enableReveal(bool _isEnabled) external onlyOwner { REVEAL_ENABLED = _isEnabled; } function enableFarming(bool _isEnabled) external onlyOwner { FARMING_ENABLED = _isEnabled; } //////////////////////////////////////// /// Proxy for NFT Operators mamnage // //////////////////////////////////////// function addOperator(address _contract, address newOperator) external onlyOwner { IOperatorManage(_contract).addOperator(newOperator); } function removeOperator(address _contract, address oldOperator) external onlyOwner { IOperatorManage(_contract).removeOperator(oldOperator); } function reclaimToken(address _contract, IERC20 anyTokens, address _admin) external onlyOwner { IOperatorManage(_contract).withdrawERC20(anyTokens, _admin); } //////////////////////////////////////////////////////// function getCreatureAmulets(uint8 _creatureType) external view returns (address[] memory) { return _getCreatureAmulets(_creatureType); } function _getCreatureAmulets(uint8 _creatureType) internal view returns (address[] memory) { return amulets[_creatureType]; } function getCreatureStat(uint8 _creatureType) external view returns ( uint16, uint16, uint16, uint16, uint16, uint16, uint16, uint16 ) { CreaturesCount storage stat = creaturesBorn[_creatureType]; return ( stat.totalNormie, stat.leftNormie, stat.totalChad, stat.leftChadToDiscover, stat.totalDegen, stat.leftDegenToDiscover, stat.leftChadFarmAttempts, stat.leftDegenFarmAttempts ); } function getWeightedChoice(uint8[] memory _weights) external view returns (uint8){ return _getWeightedChoice(_weights); } function _getWeightedChoice(uint8[] memory _weights) internal view returns (uint8){ uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); return _getWeightedChoice2(_weights, randomSeed); } function getFarmingById(uint256 _farmingId) external view returns (FarmRecord memory) { return farming[_farmingId]; } function getCommonAmuletPrices(uint256 _timestamp) external view returns (uint256[3] memory) { return _getCommonAmuletPrices(_timestamp); } function getOneAmuletPrice(address _token) external view returns (uint256) { return _getOneAmuletPrice(_token); } /////////////////////////////////////////////// /// Internals /////// /////////////////////////////////////////////// /** * @dev Save farming results in storage and mint * appropriate token (NFT, ERC20 or None) */ function _endFarming(uint256 _deployId, Result _res) internal { //TODO need refactor if EGGs will be FarmRecord storage f = farming[_deployId]; f.harvest = _res; // unstake creature ICreatures(farm.creatures).transferFrom(address(this), msg.sender, f.creatureId); eggs.burn(_deployId); // Burn EGG if (_res == Result.Fail) { //unstake land (if staked) if (ILand(farm.land).ownerOf(f.landId) == address(this)){ ILand(farm.land).transferFrom(address(this), msg.sender, f.landId); } emit Harvest( _deployId, msg.sender, uint8(_res), 0, //baseChance 0, //bonus.amuletHold, 0, //bonus.amuletBullTrend, 0 //bonus.inventoryHold ); } } function _stakeOneTool(uint8 _itemId) internal { require(IInventory(farm.inventory).balanceOf(msg.sender, _itemId) >= 1, "You must own this tool for stake!" ); //Before stake we need two checks. //1. Removed //2. Cant`t stake one tool more than one item require(userStakedTools[msg.sender][_itemId] == 0, "Tool is already staked"); //stake IInventory(farm.inventory).safeTransferFrom( msg.sender, address(this), _itemId, 1, bytes('0') ); userStakedTools[msg.sender][_itemId] = block.timestamp; } function _unstakeOneTool(uint8 _itemId) internal { require(userStakedTools[msg.sender][_itemId] > 0, "This tool is not staked yet"); require(block.timestamp - userStakedTools[msg.sender][_itemId] >= getToolUnstakeDelay(), "Cant unstake earlier than a week" ); userStakedTools[msg.sender][_itemId] = 0; IInventory(farm.inventory).safeTransferFrom( address(this), msg.sender, _itemId, 1, bytes('0') ); } function _saveCommonAmuletPrices(uint256 _timestamp) internal { //Lets check if price NOT exist for this timestamp - lets save it if (commonAmuletPrices[_timestamp][0] == 0) { for (uint8 i=0; i < COMMON_AMULETS.length; i++){ commonAmuletPrices[_timestamp][i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } } } function _checkAndSaveMaxAmuletPrice(address _amulet) internal { if (IERC20(_amulet).balanceOf(msg.sender) > maxAmuletBalances[_amulet] ) { maxAmuletBalances[_amulet] = IERC20(_amulet).balanceOf(msg.sender); } } function _getCommonAmuletPrices(uint256 _timestamp) internal view returns (uint256[3] memory) { //Lets check if price allready exist for this timestamp - just return it if (commonAmuletPrices[_timestamp][0] != 0) { return commonAmuletPrices[_timestamp]; } //If price is not exist lets get it from oracles uint256[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ res[i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } return res; } function _getCommonAmuletsHoldState(address _farmer) internal view returns (bool[3] memory) { //If token balance =0 - set false bool[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ if (IERC20(COMMON_AMULETS[i]).balanceOf(_farmer) > 0){ res[i] = true; } else { // Set to zero if token balance is 0 res[i] = false; } } return res; } function _getExistingAmuletsPrices(address[] memory _tokens) internal view returns (uint256[] memory) { uint256[] memory res = new uint256[](_tokens.length); for (uint8 i=0; i < _tokens.length; i++){ if (IERC20(_tokens[i]).balanceOf(msg.sender) > 0){ res[i] = _getOneAmuletPrice(_tokens[i]); } else { // Set to zero if token balance is 0 res[i] = 0; } } return res; } function _getOneAmuletPrice(address _token) internal view returns (uint256) { return IAmuletPriceProvider(priceProvider).getLastPrice(_token); } function _isRevelEnabled() internal view returns (bool) { return REVEAL_ENABLED; } function _reveal(uint randomSeed) internal { require ((landCount.left + allNormiesesLeft) > 0, "Sorry, no more reveal!"); //1. Lets choose Land OR Creature, % //So we have two possible results. 1 - Land, 0 - Creature. // sum of weights = 100, lets define weigth for Creature uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = uint8( uint32(allNormiesesLeft) * CREATURE_P_MULT // * 100 removed due CREATURE_P_MULT / (CREATURE_P_MULT * uint32(allNormiesesLeft) / 100 + uint32(landCount.left)) ); choiceWeight[1] = 100 - choiceWeight[0]; uint8 choice = uint8(_getWeightedChoice2(choiceWeight, randomSeed)); //Check that choice can be executed if (choice != 0 && landCount.left == 0) { //There are no more Lands. So we need change choice choice = 0; } if (choice == 0) { // create creature uint8[] memory choiceWeight0 = new uint8[](getCreatureTypeCount()); //2. Ok, Creature will be born. But what kind of? for (uint8 i = 0; i < getCreatureTypeCount(); i ++) { choiceWeight0[i] = uint8(creaturesBorn[i].leftNormie); } choice = uint8(_getWeightedChoice2(choiceWeight0, randomSeed / 0x10000)); // shift right 16 bits ICreatures(farm.creatures).mint( msg.sender, MAX_ALL_NORMIES - allNormiesesLeft, choice, //AnimalType 0, creaturesBorn[choice].totalNormie - creaturesBorn[choice].leftNormie + 1 // index ); emit Reveal(MAX_ALL_NORMIES - allNormiesesLeft, true, choice); allNormiesesLeft -= 1; creaturesBorn[choice].leftNormie -= 1; } else { // create land ILand(farm.land).mint( msg.sender, getMaxLands() - landCount.left ); emit Reveal(getMaxLands() - landCount.left , false, 0); landCount.left -= 1; } } function _getWeightedChoice2(uint8[] memory _weights, uint randomSeed) internal view returns (uint8){ uint256 sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { sum_of_weights += _weights[i]; } uint256 rnd = randomSeed % sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { if (rnd < _weights[i]) { return i; } rnd -= _weights[i]; } return 0; } /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); } /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)")); } function getCreatureTypeCount() virtual internal view returns (uint16); function getFarmingDuration() virtual internal view returns (uint); function getToolUnstakeDelay() virtual internal view returns (uint); function getNormieCountInType() virtual internal view returns (uint16); function getChadCountInType() virtual internal view returns (uint16); function getMaxLands() virtual internal view returns (uint16); function getUsersTokens(address _owner) external view returns (uint256[] memory) { return eggs.getUsersTokens(_owner); } }
stakeOneTool
function stakeOneTool(uint8 _itemId) external { _stakeOneTool(_itemId); }
/** * @dev Stake one inventory item * @param _itemId - NFT tokenId, caller must be owner of this token */
NatSpecMultiLine
v0.7.4+commit.3f05b770
MIT
ipfs://308c7d0f38216f626771d86f2b5b3091893bd5f12659a801a1f13db0060ec78f
{ "func_code_index": [ 15887, 15979 ] }
3,313
Creatures
DegensFarmBase.sol
0xd227df494367a8b769b4bf2bbebd0388a8758741
Solidity
DegenFarmBase
abstract contract DegenFarmBase is ERC1155Receiver, Ownable { enum AnimalType { Cow, Horse, Rabbit, Chicken, Pig, Cat, Dog, Goose, Goat, Sheep, Snake, Fish, Frog, Worm, Lama, Mouse, Camel, Donkey, Bee, Duck, GenesisEgg // 20 } enum Rarity { Normie, // 0 Chad, // 1 Degen, // 2 Unique // 3 } enum Result {Fail, Dung, Chad, Degen} //External conatrct addresses used with this farm. struct AddressRegistry { address land; address creatures; address inventory; address bagstoken; address dungtoken; } //Degens Farm Key numbers struct CreaturesCount { uint16 totalNormie; uint16 leftNormie; uint16 totalChad; uint16 leftChadToDiscover; uint16 totalDegen; uint16 leftDegenToDiscover; uint16 leftChadFarmAttempts; uint16 leftDegenFarmAttempts; } //Land count record struct LandCount { uint16 total; uint16 left; } // Record represent one farming act struct FarmRecord { uint256 creatureId; uint256 landId; uint256 harvestTime; uint256[] amuletsPrice1; uint256[] amuletsPrice2; Result harvest; uint256 harvestId; //new NFT tokenId bool[3] commonAmuletInitialHold; } // Bonus for better harvest struct Bonus { uint16 amuletHold; uint16 amuletBullTrend; uint16 inventoryHold; } uint8 constant public CREATURE_TYPE_COUNT_MAX = 20; //how much creatures types may be used //Creature probubility multiplier, scaled with 100. 3.00 - 300, 3.05 - 305 etc // so we need additional divide on 100 in formula uint32 constant public CREATURE_P_MULT = 230; uint16 public MAX_ALL_NORMIES = getCreatureTypeCount() * getNormieCountInType(); //subj uint256 constant public NFT_ID_MULTIPLIER = 10000; //must be set more then all Normies count uint256 constant public FARM_DUNG_AMOUNT = 250e32; //per one harvest uint16 constant public BONUS_POINTS_AMULET_HOLD = 10; uint16 constant public BONUS_POINTS_AMULET_BULL_TREND = 90; //Common Amulet addresses address[3] public COMMON_AMULETS = [ 0xa0246c9032bC3A600820415aE600c6388619A14D, 0x87d73E916D7057945c9BcD8cdd94e42A6F47f776, 0x126c121f99e1E211dF2e5f8De2d96Fa36647c855 ]; bool public REVEAL_ENABLED = false; bool public FARMING_ENABLED = false; address public priceProvider; IEggs public eggs; address[][CREATURE_TYPE_COUNT_MAX] public amulets; //amulets for creatures AddressRegistry public farm; LandCount public landCount; //common token price snapshots mapping(uint256 => uint256[3]) public commonAmuletPrices; mapping(address => uint256) public maxAmuletBalances; // mapping from user to his(her) staked tools // Index of uint256[6] represent tool NFT itemID mapping(address => uint256[6]) public userStakedTools; uint16 public allNormiesesLeft; CreaturesCount[CREATURE_TYPE_COUNT_MAX] public creaturesBorn; FarmRecord[] farming; event Reveal(uint256 indexed _tokenId, bool _isCreature, uint8 _animalType); event Harvest( uint256 indexed _eggId, address farmer, uint8 result , uint16 baseChance, uint16 amuletHold, uint16 amuletBullTrend, uint16 inventoryHold ); constructor ( address _land, address _creatures, address _inventory, address _bagstoken, address _dungtoken, IEggs _eggs ) { farm.land = _land; farm.creatures = _creatures; farm.inventory = _inventory; farm.bagstoken = _bagstoken; farm.dungtoken = _dungtoken; // Index of creaturesBorn in this initial setting // must NOT exceed CREATURE_TYPE_COUNT for (uint i = 0; i < getCreatureTypeCount(); i++) { creaturesBorn[i] = CreaturesCount( getNormieCountInType(), // totalNormie; getNormieCountInType(), // leftNormie; getChadCountInType(), // totalChad; getChadCountInType(), // leftChadToDiscover; 1, // totalDegen; 1, // leftDegenToDiscover; getNormieCountInType(), // leftChadFarmAttempts; getChadCountInType()); // leftDegenFarmAttempts; } landCount = LandCount(getMaxLands(), getMaxLands()); allNormiesesLeft = MAX_ALL_NORMIES; eggs = _eggs; } /** * @dev Changes inventory contract */ function setInventory(address _inventory) external onlyOwner { farm.inventory = _inventory; } function reveal(uint count) external { require(_isRevelEnabled(), "Please wait for reveal enabled."); require(count > 0, "Count must be positive"); require(count <= 8, "Count must less than 9"); // random limit require( IERC20(farm.bagstoken).allowance(msg.sender, address(this)) >= count*1, "Please approve your BAGS token to this contract." ); require( IERC20(farm.bagstoken).transferFrom(msg.sender, address(this), count*1) ); uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); // random seed for 8 reveals (8x32=256) for (uint i = 0; i < count; i++) { _reveal(randomSeed); randomSeed = randomSeed / 0x100000000; // shift right 32 bits } } event Log(string mess); /** * @dev Start farming process. New NFT - Egg will minted for user * @param _creatureId - NFT tokenId, caller must be owner of this token * @param _landId -- NFT tokenId, caller must be owner of this token */ function farmDeploy(uint256 _creatureId, uint256 _landId) external { require(FARMING_ENABLED == true, "Chief Farmer not enable yet"); require(ICreatures(farm.creatures).ownerOf(_creatureId) == msg.sender, "Need to be Creature Owner" ); require(ILand(farm.land).ownerOf(_landId) == msg.sender, "Need to be Land Owner" ); (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity(_creatureId); require((DegenFarmBase.Rarity)(crRarity) == Rarity.Normie || (DegenFarmBase.Rarity)(crRarity) == Rarity.Chad, "Can farm only Normie and Chad"); //Check that farming available yet if (crRarity == 0) { require(creaturesBorn[crType].leftChadToDiscover > 0, "No more chads left"); } else { require(creaturesBorn[crType].leftDegenToDiscover > 0, "No more Degen left"); } //1. Lets make amulet price snapshot //1.1. First we need creat array with properly elements count uint256[] memory prices1 = new uint256[](amulets[crType].length); uint256[] memory prices2 = new uint256[](amulets[crType].length); prices1 = _getExistingAmuletsPrices(amulets[crType]); //2.Check and save Common Amulets price(if not exist yet) _saveCommonAmuletPrices(block.timestamp); //3. Save deploy record farming.push( FarmRecord({ creatureId: _creatureId, landId: _landId, harvestTime: block.timestamp + getFarmingDuration(), amuletsPrice1: prices1, amuletsPrice2: prices2, harvest: Result.Fail, harvestId: 0, commonAmuletInitialHold: _getCommonAmuletsHoldState(msg.sender) //save initial hold state }) ); // Let's mint Egg. eggs.mint( msg.sender, // farmer farming.length - 1 // tokenId ); //STAKE LAND and Creatures!!!! ILand(farm.land).transferFrom(msg.sender, address(this), _landId); ICreatures(farm.creatures).transferFrom(msg.sender, address(this), _creatureId); } /** * @dev Finish farming process. Egg NFT will be burn * @param _deployId - NFT tokenId, caller must be owner of this token */ function harvest(uint256 _deployId) external { require(eggs.ownerOf(_deployId) == msg.sender, "This is NOT YOUR EGG"); FarmRecord storage f = farming[_deployId]; require(f.harvestTime <= block.timestamp, "To early for harvest"); //Lets Calculate Dung/CHAD-DEGEN chance Result farmingResult; Bonus memory bonus; //1. BaseChance (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity( f.creatureId ); uint16 baseChance; if (crRarity == 0) { //Try farm CHAD. So if there is no CHADs any more we must return assets if (creaturesBorn[crType].leftChadToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftChadToDiscover * 100 /(creaturesBorn[crType].leftChadFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftChadFarmAttempts -= 1; } else { //Try farm DEGEN. So if there is no DEGENSs any more we must return assets if (creaturesBorn[crType].leftDegenToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftDegenToDiscover * 100 /(creaturesBorn[crType].leftDegenFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftDegenFarmAttempts -= 1; } ////////////////////////////////////////////// // 2. Bonus for amulet token ***HOLD*** // 3. Bonus for amulets BULLs trend ////////////////////////////////////////////// bonus.amuletHold = 0; bonus.amuletBullTrend = 0; //Check common amulets _saveCommonAmuletPrices(block.timestamp); //Get current hold stae for (uint8 i = 0; i < COMMON_AMULETS.length; i ++){ if (f.commonAmuletInitialHold[i] && _getCommonAmuletsHoldState(msg.sender)[i]) { //token was hold at deploy time and now - iT IS GOOD //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(COMMON_AMULETS[i]); bonus.amuletHold = uint16( IERC20(COMMON_AMULETS[i]).balanceOf(msg.sender) * 100 / maxAmuletBalances[COMMON_AMULETS[i]] * BONUS_POINTS_AMULET_HOLD / 100 //100 used for scale ); //Lets check Bull TREND if (_getCommonAmuletPrices(f.harvestTime - getFarmingDuration())[i] < _getCommonAmuletPrices(block.timestamp)[i] ) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } //Ok, if there is NO common amulets lets check personal uint256[] memory prices2 = new uint256[](amulets[crType].length); prices2 = _getExistingAmuletsPrices(amulets[crType]); if (bonus.amuletHold != BONUS_POINTS_AMULET_HOLD) { for (uint8 i=0; i < f.amuletsPrice1.length; i ++){ if (f.amuletsPrice1[i] > 0 && prices2[i] > 0){ //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(amulets[i][crType]); bonus.amuletHold = uint16( IERC20(amulets[i][crType]).balanceOf(msg.sender) * 100 //100 used for scale / maxAmuletBalances[amulets[i][crType]] * BONUS_POINTS_AMULET_HOLD /100 ); //Lets check Bull TREND if (f.amuletsPrice1[i] < prices2[i]) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } } ////////////////////////////////////////////// ////////////////////////////////////////////// //4. Bonus for inventory ////////////////////////////////////////////// bonus.inventoryHold = 0; if (userStakedTools[msg.sender].length > 0) { for (uint8 i=0; i<userStakedTools[msg.sender].length; i++) { if (userStakedTools[msg.sender][i] > 0){ bonus.inventoryHold = bonus.inventoryHold + IInventory(farm.inventory).getToolBoost(i); } } } ////////////////////////////////////////////// uint16 allBonus = bonus.amuletHold + bonus.amuletBullTrend + bonus.inventoryHold; uint8 chanceOfRarityUP = uint8( (baseChance + allBonus) * 100 / (100 + allBonus) ); uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = chanceOfRarityUP; choiceWeight[1] = 100 - chanceOfRarityUP; uint8 choice = uint8(_getWeightedChoice(choiceWeight)); if (choice == 0) { f.harvestId = (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId; // Mint new chad/degen uint32 index; //Decrease appropriate CREATRURE COUNT if (crRarity + 1 == uint8(Rarity.Chad)) { index = creaturesBorn[crType].totalChad - creaturesBorn[crType].leftChadToDiscover + 1; creaturesBorn[crType].leftChadToDiscover -= 1; farmingResult = Result.Chad; } else if (crRarity + 1 == uint8(Rarity.Degen)) { index = creaturesBorn[crType].totalDegen - creaturesBorn[crType].leftDegenToDiscover + 1; creaturesBorn[crType].leftDegenToDiscover -= 1; farmingResult = Result.Degen; } ICreatures(farm.creatures).mint( msg.sender, (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId, // new iD crType, //AnimalType crRarity + 1, index // index ); } else { //Mint new dung IDung(farm.dungtoken).mint(msg.sender, FARM_DUNG_AMOUNT); farmingResult = Result.Dung; } //BURN Land ILand(farm.land).burn(f.landId); _endFarming(_deployId, farmingResult); emit Harvest( _deployId, msg.sender, uint8(farmingResult), baseChance, bonus.amuletHold, bonus.amuletBullTrend, bonus.inventoryHold ); } /** * @dev Stake one inventory item * @param _itemId - NFT tokenId, caller must be owner of this token */ function stakeOneTool(uint8 _itemId) external { _stakeOneTool(_itemId); } /** * @dev UnStake one inventory item * @param _itemId - NFT tokenId */ function unstakeOneTool(uint8 _itemId) external { _unstakeOneTool(_itemId); } ///////////////////////////////////////////////////// //// Admin functions /////// ///////////////////////////////////////////////////// function setOneCommonAmulet(uint8 _index, address _token) external onlyOwner { COMMON_AMULETS[_index] = _token; } function setAmuletForOneCreature(uint8 _index, address[] memory _tokens) external onlyOwner { delete amulets[_index]; amulets[_index] = _tokens; } function setPriceProvider(address _priceProvider) external onlyOwner { priceProvider = _priceProvider; } function enableReveal(bool _isEnabled) external onlyOwner { REVEAL_ENABLED = _isEnabled; } function enableFarming(bool _isEnabled) external onlyOwner { FARMING_ENABLED = _isEnabled; } //////////////////////////////////////// /// Proxy for NFT Operators mamnage // //////////////////////////////////////// function addOperator(address _contract, address newOperator) external onlyOwner { IOperatorManage(_contract).addOperator(newOperator); } function removeOperator(address _contract, address oldOperator) external onlyOwner { IOperatorManage(_contract).removeOperator(oldOperator); } function reclaimToken(address _contract, IERC20 anyTokens, address _admin) external onlyOwner { IOperatorManage(_contract).withdrawERC20(anyTokens, _admin); } //////////////////////////////////////////////////////// function getCreatureAmulets(uint8 _creatureType) external view returns (address[] memory) { return _getCreatureAmulets(_creatureType); } function _getCreatureAmulets(uint8 _creatureType) internal view returns (address[] memory) { return amulets[_creatureType]; } function getCreatureStat(uint8 _creatureType) external view returns ( uint16, uint16, uint16, uint16, uint16, uint16, uint16, uint16 ) { CreaturesCount storage stat = creaturesBorn[_creatureType]; return ( stat.totalNormie, stat.leftNormie, stat.totalChad, stat.leftChadToDiscover, stat.totalDegen, stat.leftDegenToDiscover, stat.leftChadFarmAttempts, stat.leftDegenFarmAttempts ); } function getWeightedChoice(uint8[] memory _weights) external view returns (uint8){ return _getWeightedChoice(_weights); } function _getWeightedChoice(uint8[] memory _weights) internal view returns (uint8){ uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); return _getWeightedChoice2(_weights, randomSeed); } function getFarmingById(uint256 _farmingId) external view returns (FarmRecord memory) { return farming[_farmingId]; } function getCommonAmuletPrices(uint256 _timestamp) external view returns (uint256[3] memory) { return _getCommonAmuletPrices(_timestamp); } function getOneAmuletPrice(address _token) external view returns (uint256) { return _getOneAmuletPrice(_token); } /////////////////////////////////////////////// /// Internals /////// /////////////////////////////////////////////// /** * @dev Save farming results in storage and mint * appropriate token (NFT, ERC20 or None) */ function _endFarming(uint256 _deployId, Result _res) internal { //TODO need refactor if EGGs will be FarmRecord storage f = farming[_deployId]; f.harvest = _res; // unstake creature ICreatures(farm.creatures).transferFrom(address(this), msg.sender, f.creatureId); eggs.burn(_deployId); // Burn EGG if (_res == Result.Fail) { //unstake land (if staked) if (ILand(farm.land).ownerOf(f.landId) == address(this)){ ILand(farm.land).transferFrom(address(this), msg.sender, f.landId); } emit Harvest( _deployId, msg.sender, uint8(_res), 0, //baseChance 0, //bonus.amuletHold, 0, //bonus.amuletBullTrend, 0 //bonus.inventoryHold ); } } function _stakeOneTool(uint8 _itemId) internal { require(IInventory(farm.inventory).balanceOf(msg.sender, _itemId) >= 1, "You must own this tool for stake!" ); //Before stake we need two checks. //1. Removed //2. Cant`t stake one tool more than one item require(userStakedTools[msg.sender][_itemId] == 0, "Tool is already staked"); //stake IInventory(farm.inventory).safeTransferFrom( msg.sender, address(this), _itemId, 1, bytes('0') ); userStakedTools[msg.sender][_itemId] = block.timestamp; } function _unstakeOneTool(uint8 _itemId) internal { require(userStakedTools[msg.sender][_itemId] > 0, "This tool is not staked yet"); require(block.timestamp - userStakedTools[msg.sender][_itemId] >= getToolUnstakeDelay(), "Cant unstake earlier than a week" ); userStakedTools[msg.sender][_itemId] = 0; IInventory(farm.inventory).safeTransferFrom( address(this), msg.sender, _itemId, 1, bytes('0') ); } function _saveCommonAmuletPrices(uint256 _timestamp) internal { //Lets check if price NOT exist for this timestamp - lets save it if (commonAmuletPrices[_timestamp][0] == 0) { for (uint8 i=0; i < COMMON_AMULETS.length; i++){ commonAmuletPrices[_timestamp][i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } } } function _checkAndSaveMaxAmuletPrice(address _amulet) internal { if (IERC20(_amulet).balanceOf(msg.sender) > maxAmuletBalances[_amulet] ) { maxAmuletBalances[_amulet] = IERC20(_amulet).balanceOf(msg.sender); } } function _getCommonAmuletPrices(uint256 _timestamp) internal view returns (uint256[3] memory) { //Lets check if price allready exist for this timestamp - just return it if (commonAmuletPrices[_timestamp][0] != 0) { return commonAmuletPrices[_timestamp]; } //If price is not exist lets get it from oracles uint256[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ res[i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } return res; } function _getCommonAmuletsHoldState(address _farmer) internal view returns (bool[3] memory) { //If token balance =0 - set false bool[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ if (IERC20(COMMON_AMULETS[i]).balanceOf(_farmer) > 0){ res[i] = true; } else { // Set to zero if token balance is 0 res[i] = false; } } return res; } function _getExistingAmuletsPrices(address[] memory _tokens) internal view returns (uint256[] memory) { uint256[] memory res = new uint256[](_tokens.length); for (uint8 i=0; i < _tokens.length; i++){ if (IERC20(_tokens[i]).balanceOf(msg.sender) > 0){ res[i] = _getOneAmuletPrice(_tokens[i]); } else { // Set to zero if token balance is 0 res[i] = 0; } } return res; } function _getOneAmuletPrice(address _token) internal view returns (uint256) { return IAmuletPriceProvider(priceProvider).getLastPrice(_token); } function _isRevelEnabled() internal view returns (bool) { return REVEAL_ENABLED; } function _reveal(uint randomSeed) internal { require ((landCount.left + allNormiesesLeft) > 0, "Sorry, no more reveal!"); //1. Lets choose Land OR Creature, % //So we have two possible results. 1 - Land, 0 - Creature. // sum of weights = 100, lets define weigth for Creature uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = uint8( uint32(allNormiesesLeft) * CREATURE_P_MULT // * 100 removed due CREATURE_P_MULT / (CREATURE_P_MULT * uint32(allNormiesesLeft) / 100 + uint32(landCount.left)) ); choiceWeight[1] = 100 - choiceWeight[0]; uint8 choice = uint8(_getWeightedChoice2(choiceWeight, randomSeed)); //Check that choice can be executed if (choice != 0 && landCount.left == 0) { //There are no more Lands. So we need change choice choice = 0; } if (choice == 0) { // create creature uint8[] memory choiceWeight0 = new uint8[](getCreatureTypeCount()); //2. Ok, Creature will be born. But what kind of? for (uint8 i = 0; i < getCreatureTypeCount(); i ++) { choiceWeight0[i] = uint8(creaturesBorn[i].leftNormie); } choice = uint8(_getWeightedChoice2(choiceWeight0, randomSeed / 0x10000)); // shift right 16 bits ICreatures(farm.creatures).mint( msg.sender, MAX_ALL_NORMIES - allNormiesesLeft, choice, //AnimalType 0, creaturesBorn[choice].totalNormie - creaturesBorn[choice].leftNormie + 1 // index ); emit Reveal(MAX_ALL_NORMIES - allNormiesesLeft, true, choice); allNormiesesLeft -= 1; creaturesBorn[choice].leftNormie -= 1; } else { // create land ILand(farm.land).mint( msg.sender, getMaxLands() - landCount.left ); emit Reveal(getMaxLands() - landCount.left , false, 0); landCount.left -= 1; } } function _getWeightedChoice2(uint8[] memory _weights, uint randomSeed) internal view returns (uint8){ uint256 sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { sum_of_weights += _weights[i]; } uint256 rnd = randomSeed % sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { if (rnd < _weights[i]) { return i; } rnd -= _weights[i]; } return 0; } /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); } /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)")); } function getCreatureTypeCount() virtual internal view returns (uint16); function getFarmingDuration() virtual internal view returns (uint); function getToolUnstakeDelay() virtual internal view returns (uint); function getNormieCountInType() virtual internal view returns (uint16); function getChadCountInType() virtual internal view returns (uint16); function getMaxLands() virtual internal view returns (uint16); function getUsersTokens(address _owner) external view returns (uint256[] memory) { return eggs.getUsersTokens(_owner); } }
unstakeOneTool
function unstakeOneTool(uint8 _itemId) external { _unstakeOneTool(_itemId); }
/** * @dev UnStake one inventory item * @param _itemId - NFT tokenId */
NatSpecMultiLine
v0.7.4+commit.3f05b770
MIT
ipfs://308c7d0f38216f626771d86f2b5b3091893bd5f12659a801a1f13db0060ec78f
{ "func_code_index": [ 16080, 16176 ] }
3,314
Creatures
DegensFarmBase.sol
0xd227df494367a8b769b4bf2bbebd0388a8758741
Solidity
DegenFarmBase
abstract contract DegenFarmBase is ERC1155Receiver, Ownable { enum AnimalType { Cow, Horse, Rabbit, Chicken, Pig, Cat, Dog, Goose, Goat, Sheep, Snake, Fish, Frog, Worm, Lama, Mouse, Camel, Donkey, Bee, Duck, GenesisEgg // 20 } enum Rarity { Normie, // 0 Chad, // 1 Degen, // 2 Unique // 3 } enum Result {Fail, Dung, Chad, Degen} //External conatrct addresses used with this farm. struct AddressRegistry { address land; address creatures; address inventory; address bagstoken; address dungtoken; } //Degens Farm Key numbers struct CreaturesCount { uint16 totalNormie; uint16 leftNormie; uint16 totalChad; uint16 leftChadToDiscover; uint16 totalDegen; uint16 leftDegenToDiscover; uint16 leftChadFarmAttempts; uint16 leftDegenFarmAttempts; } //Land count record struct LandCount { uint16 total; uint16 left; } // Record represent one farming act struct FarmRecord { uint256 creatureId; uint256 landId; uint256 harvestTime; uint256[] amuletsPrice1; uint256[] amuletsPrice2; Result harvest; uint256 harvestId; //new NFT tokenId bool[3] commonAmuletInitialHold; } // Bonus for better harvest struct Bonus { uint16 amuletHold; uint16 amuletBullTrend; uint16 inventoryHold; } uint8 constant public CREATURE_TYPE_COUNT_MAX = 20; //how much creatures types may be used //Creature probubility multiplier, scaled with 100. 3.00 - 300, 3.05 - 305 etc // so we need additional divide on 100 in formula uint32 constant public CREATURE_P_MULT = 230; uint16 public MAX_ALL_NORMIES = getCreatureTypeCount() * getNormieCountInType(); //subj uint256 constant public NFT_ID_MULTIPLIER = 10000; //must be set more then all Normies count uint256 constant public FARM_DUNG_AMOUNT = 250e32; //per one harvest uint16 constant public BONUS_POINTS_AMULET_HOLD = 10; uint16 constant public BONUS_POINTS_AMULET_BULL_TREND = 90; //Common Amulet addresses address[3] public COMMON_AMULETS = [ 0xa0246c9032bC3A600820415aE600c6388619A14D, 0x87d73E916D7057945c9BcD8cdd94e42A6F47f776, 0x126c121f99e1E211dF2e5f8De2d96Fa36647c855 ]; bool public REVEAL_ENABLED = false; bool public FARMING_ENABLED = false; address public priceProvider; IEggs public eggs; address[][CREATURE_TYPE_COUNT_MAX] public amulets; //amulets for creatures AddressRegistry public farm; LandCount public landCount; //common token price snapshots mapping(uint256 => uint256[3]) public commonAmuletPrices; mapping(address => uint256) public maxAmuletBalances; // mapping from user to his(her) staked tools // Index of uint256[6] represent tool NFT itemID mapping(address => uint256[6]) public userStakedTools; uint16 public allNormiesesLeft; CreaturesCount[CREATURE_TYPE_COUNT_MAX] public creaturesBorn; FarmRecord[] farming; event Reveal(uint256 indexed _tokenId, bool _isCreature, uint8 _animalType); event Harvest( uint256 indexed _eggId, address farmer, uint8 result , uint16 baseChance, uint16 amuletHold, uint16 amuletBullTrend, uint16 inventoryHold ); constructor ( address _land, address _creatures, address _inventory, address _bagstoken, address _dungtoken, IEggs _eggs ) { farm.land = _land; farm.creatures = _creatures; farm.inventory = _inventory; farm.bagstoken = _bagstoken; farm.dungtoken = _dungtoken; // Index of creaturesBorn in this initial setting // must NOT exceed CREATURE_TYPE_COUNT for (uint i = 0; i < getCreatureTypeCount(); i++) { creaturesBorn[i] = CreaturesCount( getNormieCountInType(), // totalNormie; getNormieCountInType(), // leftNormie; getChadCountInType(), // totalChad; getChadCountInType(), // leftChadToDiscover; 1, // totalDegen; 1, // leftDegenToDiscover; getNormieCountInType(), // leftChadFarmAttempts; getChadCountInType()); // leftDegenFarmAttempts; } landCount = LandCount(getMaxLands(), getMaxLands()); allNormiesesLeft = MAX_ALL_NORMIES; eggs = _eggs; } /** * @dev Changes inventory contract */ function setInventory(address _inventory) external onlyOwner { farm.inventory = _inventory; } function reveal(uint count) external { require(_isRevelEnabled(), "Please wait for reveal enabled."); require(count > 0, "Count must be positive"); require(count <= 8, "Count must less than 9"); // random limit require( IERC20(farm.bagstoken).allowance(msg.sender, address(this)) >= count*1, "Please approve your BAGS token to this contract." ); require( IERC20(farm.bagstoken).transferFrom(msg.sender, address(this), count*1) ); uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); // random seed for 8 reveals (8x32=256) for (uint i = 0; i < count; i++) { _reveal(randomSeed); randomSeed = randomSeed / 0x100000000; // shift right 32 bits } } event Log(string mess); /** * @dev Start farming process. New NFT - Egg will minted for user * @param _creatureId - NFT tokenId, caller must be owner of this token * @param _landId -- NFT tokenId, caller must be owner of this token */ function farmDeploy(uint256 _creatureId, uint256 _landId) external { require(FARMING_ENABLED == true, "Chief Farmer not enable yet"); require(ICreatures(farm.creatures).ownerOf(_creatureId) == msg.sender, "Need to be Creature Owner" ); require(ILand(farm.land).ownerOf(_landId) == msg.sender, "Need to be Land Owner" ); (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity(_creatureId); require((DegenFarmBase.Rarity)(crRarity) == Rarity.Normie || (DegenFarmBase.Rarity)(crRarity) == Rarity.Chad, "Can farm only Normie and Chad"); //Check that farming available yet if (crRarity == 0) { require(creaturesBorn[crType].leftChadToDiscover > 0, "No more chads left"); } else { require(creaturesBorn[crType].leftDegenToDiscover > 0, "No more Degen left"); } //1. Lets make amulet price snapshot //1.1. First we need creat array with properly elements count uint256[] memory prices1 = new uint256[](amulets[crType].length); uint256[] memory prices2 = new uint256[](amulets[crType].length); prices1 = _getExistingAmuletsPrices(amulets[crType]); //2.Check and save Common Amulets price(if not exist yet) _saveCommonAmuletPrices(block.timestamp); //3. Save deploy record farming.push( FarmRecord({ creatureId: _creatureId, landId: _landId, harvestTime: block.timestamp + getFarmingDuration(), amuletsPrice1: prices1, amuletsPrice2: prices2, harvest: Result.Fail, harvestId: 0, commonAmuletInitialHold: _getCommonAmuletsHoldState(msg.sender) //save initial hold state }) ); // Let's mint Egg. eggs.mint( msg.sender, // farmer farming.length - 1 // tokenId ); //STAKE LAND and Creatures!!!! ILand(farm.land).transferFrom(msg.sender, address(this), _landId); ICreatures(farm.creatures).transferFrom(msg.sender, address(this), _creatureId); } /** * @dev Finish farming process. Egg NFT will be burn * @param _deployId - NFT tokenId, caller must be owner of this token */ function harvest(uint256 _deployId) external { require(eggs.ownerOf(_deployId) == msg.sender, "This is NOT YOUR EGG"); FarmRecord storage f = farming[_deployId]; require(f.harvestTime <= block.timestamp, "To early for harvest"); //Lets Calculate Dung/CHAD-DEGEN chance Result farmingResult; Bonus memory bonus; //1. BaseChance (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity( f.creatureId ); uint16 baseChance; if (crRarity == 0) { //Try farm CHAD. So if there is no CHADs any more we must return assets if (creaturesBorn[crType].leftChadToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftChadToDiscover * 100 /(creaturesBorn[crType].leftChadFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftChadFarmAttempts -= 1; } else { //Try farm DEGEN. So if there is no DEGENSs any more we must return assets if (creaturesBorn[crType].leftDegenToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftDegenToDiscover * 100 /(creaturesBorn[crType].leftDegenFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftDegenFarmAttempts -= 1; } ////////////////////////////////////////////// // 2. Bonus for amulet token ***HOLD*** // 3. Bonus for amulets BULLs trend ////////////////////////////////////////////// bonus.amuletHold = 0; bonus.amuletBullTrend = 0; //Check common amulets _saveCommonAmuletPrices(block.timestamp); //Get current hold stae for (uint8 i = 0; i < COMMON_AMULETS.length; i ++){ if (f.commonAmuletInitialHold[i] && _getCommonAmuletsHoldState(msg.sender)[i]) { //token was hold at deploy time and now - iT IS GOOD //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(COMMON_AMULETS[i]); bonus.amuletHold = uint16( IERC20(COMMON_AMULETS[i]).balanceOf(msg.sender) * 100 / maxAmuletBalances[COMMON_AMULETS[i]] * BONUS_POINTS_AMULET_HOLD / 100 //100 used for scale ); //Lets check Bull TREND if (_getCommonAmuletPrices(f.harvestTime - getFarmingDuration())[i] < _getCommonAmuletPrices(block.timestamp)[i] ) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } //Ok, if there is NO common amulets lets check personal uint256[] memory prices2 = new uint256[](amulets[crType].length); prices2 = _getExistingAmuletsPrices(amulets[crType]); if (bonus.amuletHold != BONUS_POINTS_AMULET_HOLD) { for (uint8 i=0; i < f.amuletsPrice1.length; i ++){ if (f.amuletsPrice1[i] > 0 && prices2[i] > 0){ //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(amulets[i][crType]); bonus.amuletHold = uint16( IERC20(amulets[i][crType]).balanceOf(msg.sender) * 100 //100 used for scale / maxAmuletBalances[amulets[i][crType]] * BONUS_POINTS_AMULET_HOLD /100 ); //Lets check Bull TREND if (f.amuletsPrice1[i] < prices2[i]) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } } ////////////////////////////////////////////// ////////////////////////////////////////////// //4. Bonus for inventory ////////////////////////////////////////////// bonus.inventoryHold = 0; if (userStakedTools[msg.sender].length > 0) { for (uint8 i=0; i<userStakedTools[msg.sender].length; i++) { if (userStakedTools[msg.sender][i] > 0){ bonus.inventoryHold = bonus.inventoryHold + IInventory(farm.inventory).getToolBoost(i); } } } ////////////////////////////////////////////// uint16 allBonus = bonus.amuletHold + bonus.amuletBullTrend + bonus.inventoryHold; uint8 chanceOfRarityUP = uint8( (baseChance + allBonus) * 100 / (100 + allBonus) ); uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = chanceOfRarityUP; choiceWeight[1] = 100 - chanceOfRarityUP; uint8 choice = uint8(_getWeightedChoice(choiceWeight)); if (choice == 0) { f.harvestId = (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId; // Mint new chad/degen uint32 index; //Decrease appropriate CREATRURE COUNT if (crRarity + 1 == uint8(Rarity.Chad)) { index = creaturesBorn[crType].totalChad - creaturesBorn[crType].leftChadToDiscover + 1; creaturesBorn[crType].leftChadToDiscover -= 1; farmingResult = Result.Chad; } else if (crRarity + 1 == uint8(Rarity.Degen)) { index = creaturesBorn[crType].totalDegen - creaturesBorn[crType].leftDegenToDiscover + 1; creaturesBorn[crType].leftDegenToDiscover -= 1; farmingResult = Result.Degen; } ICreatures(farm.creatures).mint( msg.sender, (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId, // new iD crType, //AnimalType crRarity + 1, index // index ); } else { //Mint new dung IDung(farm.dungtoken).mint(msg.sender, FARM_DUNG_AMOUNT); farmingResult = Result.Dung; } //BURN Land ILand(farm.land).burn(f.landId); _endFarming(_deployId, farmingResult); emit Harvest( _deployId, msg.sender, uint8(farmingResult), baseChance, bonus.amuletHold, bonus.amuletBullTrend, bonus.inventoryHold ); } /** * @dev Stake one inventory item * @param _itemId - NFT tokenId, caller must be owner of this token */ function stakeOneTool(uint8 _itemId) external { _stakeOneTool(_itemId); } /** * @dev UnStake one inventory item * @param _itemId - NFT tokenId */ function unstakeOneTool(uint8 _itemId) external { _unstakeOneTool(_itemId); } ///////////////////////////////////////////////////// //// Admin functions /////// ///////////////////////////////////////////////////// function setOneCommonAmulet(uint8 _index, address _token) external onlyOwner { COMMON_AMULETS[_index] = _token; } function setAmuletForOneCreature(uint8 _index, address[] memory _tokens) external onlyOwner { delete amulets[_index]; amulets[_index] = _tokens; } function setPriceProvider(address _priceProvider) external onlyOwner { priceProvider = _priceProvider; } function enableReveal(bool _isEnabled) external onlyOwner { REVEAL_ENABLED = _isEnabled; } function enableFarming(bool _isEnabled) external onlyOwner { FARMING_ENABLED = _isEnabled; } //////////////////////////////////////// /// Proxy for NFT Operators mamnage // //////////////////////////////////////// function addOperator(address _contract, address newOperator) external onlyOwner { IOperatorManage(_contract).addOperator(newOperator); } function removeOperator(address _contract, address oldOperator) external onlyOwner { IOperatorManage(_contract).removeOperator(oldOperator); } function reclaimToken(address _contract, IERC20 anyTokens, address _admin) external onlyOwner { IOperatorManage(_contract).withdrawERC20(anyTokens, _admin); } //////////////////////////////////////////////////////// function getCreatureAmulets(uint8 _creatureType) external view returns (address[] memory) { return _getCreatureAmulets(_creatureType); } function _getCreatureAmulets(uint8 _creatureType) internal view returns (address[] memory) { return amulets[_creatureType]; } function getCreatureStat(uint8 _creatureType) external view returns ( uint16, uint16, uint16, uint16, uint16, uint16, uint16, uint16 ) { CreaturesCount storage stat = creaturesBorn[_creatureType]; return ( stat.totalNormie, stat.leftNormie, stat.totalChad, stat.leftChadToDiscover, stat.totalDegen, stat.leftDegenToDiscover, stat.leftChadFarmAttempts, stat.leftDegenFarmAttempts ); } function getWeightedChoice(uint8[] memory _weights) external view returns (uint8){ return _getWeightedChoice(_weights); } function _getWeightedChoice(uint8[] memory _weights) internal view returns (uint8){ uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); return _getWeightedChoice2(_weights, randomSeed); } function getFarmingById(uint256 _farmingId) external view returns (FarmRecord memory) { return farming[_farmingId]; } function getCommonAmuletPrices(uint256 _timestamp) external view returns (uint256[3] memory) { return _getCommonAmuletPrices(_timestamp); } function getOneAmuletPrice(address _token) external view returns (uint256) { return _getOneAmuletPrice(_token); } /////////////////////////////////////////////// /// Internals /////// /////////////////////////////////////////////// /** * @dev Save farming results in storage and mint * appropriate token (NFT, ERC20 or None) */ function _endFarming(uint256 _deployId, Result _res) internal { //TODO need refactor if EGGs will be FarmRecord storage f = farming[_deployId]; f.harvest = _res; // unstake creature ICreatures(farm.creatures).transferFrom(address(this), msg.sender, f.creatureId); eggs.burn(_deployId); // Burn EGG if (_res == Result.Fail) { //unstake land (if staked) if (ILand(farm.land).ownerOf(f.landId) == address(this)){ ILand(farm.land).transferFrom(address(this), msg.sender, f.landId); } emit Harvest( _deployId, msg.sender, uint8(_res), 0, //baseChance 0, //bonus.amuletHold, 0, //bonus.amuletBullTrend, 0 //bonus.inventoryHold ); } } function _stakeOneTool(uint8 _itemId) internal { require(IInventory(farm.inventory).balanceOf(msg.sender, _itemId) >= 1, "You must own this tool for stake!" ); //Before stake we need two checks. //1. Removed //2. Cant`t stake one tool more than one item require(userStakedTools[msg.sender][_itemId] == 0, "Tool is already staked"); //stake IInventory(farm.inventory).safeTransferFrom( msg.sender, address(this), _itemId, 1, bytes('0') ); userStakedTools[msg.sender][_itemId] = block.timestamp; } function _unstakeOneTool(uint8 _itemId) internal { require(userStakedTools[msg.sender][_itemId] > 0, "This tool is not staked yet"); require(block.timestamp - userStakedTools[msg.sender][_itemId] >= getToolUnstakeDelay(), "Cant unstake earlier than a week" ); userStakedTools[msg.sender][_itemId] = 0; IInventory(farm.inventory).safeTransferFrom( address(this), msg.sender, _itemId, 1, bytes('0') ); } function _saveCommonAmuletPrices(uint256 _timestamp) internal { //Lets check if price NOT exist for this timestamp - lets save it if (commonAmuletPrices[_timestamp][0] == 0) { for (uint8 i=0; i < COMMON_AMULETS.length; i++){ commonAmuletPrices[_timestamp][i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } } } function _checkAndSaveMaxAmuletPrice(address _amulet) internal { if (IERC20(_amulet).balanceOf(msg.sender) > maxAmuletBalances[_amulet] ) { maxAmuletBalances[_amulet] = IERC20(_amulet).balanceOf(msg.sender); } } function _getCommonAmuletPrices(uint256 _timestamp) internal view returns (uint256[3] memory) { //Lets check if price allready exist for this timestamp - just return it if (commonAmuletPrices[_timestamp][0] != 0) { return commonAmuletPrices[_timestamp]; } //If price is not exist lets get it from oracles uint256[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ res[i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } return res; } function _getCommonAmuletsHoldState(address _farmer) internal view returns (bool[3] memory) { //If token balance =0 - set false bool[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ if (IERC20(COMMON_AMULETS[i]).balanceOf(_farmer) > 0){ res[i] = true; } else { // Set to zero if token balance is 0 res[i] = false; } } return res; } function _getExistingAmuletsPrices(address[] memory _tokens) internal view returns (uint256[] memory) { uint256[] memory res = new uint256[](_tokens.length); for (uint8 i=0; i < _tokens.length; i++){ if (IERC20(_tokens[i]).balanceOf(msg.sender) > 0){ res[i] = _getOneAmuletPrice(_tokens[i]); } else { // Set to zero if token balance is 0 res[i] = 0; } } return res; } function _getOneAmuletPrice(address _token) internal view returns (uint256) { return IAmuletPriceProvider(priceProvider).getLastPrice(_token); } function _isRevelEnabled() internal view returns (bool) { return REVEAL_ENABLED; } function _reveal(uint randomSeed) internal { require ((landCount.left + allNormiesesLeft) > 0, "Sorry, no more reveal!"); //1. Lets choose Land OR Creature, % //So we have two possible results. 1 - Land, 0 - Creature. // sum of weights = 100, lets define weigth for Creature uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = uint8( uint32(allNormiesesLeft) * CREATURE_P_MULT // * 100 removed due CREATURE_P_MULT / (CREATURE_P_MULT * uint32(allNormiesesLeft) / 100 + uint32(landCount.left)) ); choiceWeight[1] = 100 - choiceWeight[0]; uint8 choice = uint8(_getWeightedChoice2(choiceWeight, randomSeed)); //Check that choice can be executed if (choice != 0 && landCount.left == 0) { //There are no more Lands. So we need change choice choice = 0; } if (choice == 0) { // create creature uint8[] memory choiceWeight0 = new uint8[](getCreatureTypeCount()); //2. Ok, Creature will be born. But what kind of? for (uint8 i = 0; i < getCreatureTypeCount(); i ++) { choiceWeight0[i] = uint8(creaturesBorn[i].leftNormie); } choice = uint8(_getWeightedChoice2(choiceWeight0, randomSeed / 0x10000)); // shift right 16 bits ICreatures(farm.creatures).mint( msg.sender, MAX_ALL_NORMIES - allNormiesesLeft, choice, //AnimalType 0, creaturesBorn[choice].totalNormie - creaturesBorn[choice].leftNormie + 1 // index ); emit Reveal(MAX_ALL_NORMIES - allNormiesesLeft, true, choice); allNormiesesLeft -= 1; creaturesBorn[choice].leftNormie -= 1; } else { // create land ILand(farm.land).mint( msg.sender, getMaxLands() - landCount.left ); emit Reveal(getMaxLands() - landCount.left , false, 0); landCount.left -= 1; } } function _getWeightedChoice2(uint8[] memory _weights, uint randomSeed) internal view returns (uint8){ uint256 sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { sum_of_weights += _weights[i]; } uint256 rnd = randomSeed % sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { if (rnd < _weights[i]) { return i; } rnd -= _weights[i]; } return 0; } /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); } /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)")); } function getCreatureTypeCount() virtual internal view returns (uint16); function getFarmingDuration() virtual internal view returns (uint); function getToolUnstakeDelay() virtual internal view returns (uint); function getNormieCountInType() virtual internal view returns (uint16); function getChadCountInType() virtual internal view returns (uint16); function getMaxLands() virtual internal view returns (uint16); function getUsersTokens(address _owner) external view returns (uint256[] memory) { return eggs.getUsersTokens(_owner); } }
setOneCommonAmulet
function setOneCommonAmulet(uint8 _index, address _token) external onlyOwner { COMMON_AMULETS[_index] = _token; }
///////////////////////////////////////////////////// //// Admin functions /////// /////////////////////////////////////////////////////
NatSpecSingleLine
v0.7.4+commit.3f05b770
MIT
ipfs://308c7d0f38216f626771d86f2b5b3091893bd5f12659a801a1f13db0060ec78f
{ "func_code_index": [ 16356, 16488 ] }
3,315
Creatures
DegensFarmBase.sol
0xd227df494367a8b769b4bf2bbebd0388a8758741
Solidity
DegenFarmBase
abstract contract DegenFarmBase is ERC1155Receiver, Ownable { enum AnimalType { Cow, Horse, Rabbit, Chicken, Pig, Cat, Dog, Goose, Goat, Sheep, Snake, Fish, Frog, Worm, Lama, Mouse, Camel, Donkey, Bee, Duck, GenesisEgg // 20 } enum Rarity { Normie, // 0 Chad, // 1 Degen, // 2 Unique // 3 } enum Result {Fail, Dung, Chad, Degen} //External conatrct addresses used with this farm. struct AddressRegistry { address land; address creatures; address inventory; address bagstoken; address dungtoken; } //Degens Farm Key numbers struct CreaturesCount { uint16 totalNormie; uint16 leftNormie; uint16 totalChad; uint16 leftChadToDiscover; uint16 totalDegen; uint16 leftDegenToDiscover; uint16 leftChadFarmAttempts; uint16 leftDegenFarmAttempts; } //Land count record struct LandCount { uint16 total; uint16 left; } // Record represent one farming act struct FarmRecord { uint256 creatureId; uint256 landId; uint256 harvestTime; uint256[] amuletsPrice1; uint256[] amuletsPrice2; Result harvest; uint256 harvestId; //new NFT tokenId bool[3] commonAmuletInitialHold; } // Bonus for better harvest struct Bonus { uint16 amuletHold; uint16 amuletBullTrend; uint16 inventoryHold; } uint8 constant public CREATURE_TYPE_COUNT_MAX = 20; //how much creatures types may be used //Creature probubility multiplier, scaled with 100. 3.00 - 300, 3.05 - 305 etc // so we need additional divide on 100 in formula uint32 constant public CREATURE_P_MULT = 230; uint16 public MAX_ALL_NORMIES = getCreatureTypeCount() * getNormieCountInType(); //subj uint256 constant public NFT_ID_MULTIPLIER = 10000; //must be set more then all Normies count uint256 constant public FARM_DUNG_AMOUNT = 250e32; //per one harvest uint16 constant public BONUS_POINTS_AMULET_HOLD = 10; uint16 constant public BONUS_POINTS_AMULET_BULL_TREND = 90; //Common Amulet addresses address[3] public COMMON_AMULETS = [ 0xa0246c9032bC3A600820415aE600c6388619A14D, 0x87d73E916D7057945c9BcD8cdd94e42A6F47f776, 0x126c121f99e1E211dF2e5f8De2d96Fa36647c855 ]; bool public REVEAL_ENABLED = false; bool public FARMING_ENABLED = false; address public priceProvider; IEggs public eggs; address[][CREATURE_TYPE_COUNT_MAX] public amulets; //amulets for creatures AddressRegistry public farm; LandCount public landCount; //common token price snapshots mapping(uint256 => uint256[3]) public commonAmuletPrices; mapping(address => uint256) public maxAmuletBalances; // mapping from user to his(her) staked tools // Index of uint256[6] represent tool NFT itemID mapping(address => uint256[6]) public userStakedTools; uint16 public allNormiesesLeft; CreaturesCount[CREATURE_TYPE_COUNT_MAX] public creaturesBorn; FarmRecord[] farming; event Reveal(uint256 indexed _tokenId, bool _isCreature, uint8 _animalType); event Harvest( uint256 indexed _eggId, address farmer, uint8 result , uint16 baseChance, uint16 amuletHold, uint16 amuletBullTrend, uint16 inventoryHold ); constructor ( address _land, address _creatures, address _inventory, address _bagstoken, address _dungtoken, IEggs _eggs ) { farm.land = _land; farm.creatures = _creatures; farm.inventory = _inventory; farm.bagstoken = _bagstoken; farm.dungtoken = _dungtoken; // Index of creaturesBorn in this initial setting // must NOT exceed CREATURE_TYPE_COUNT for (uint i = 0; i < getCreatureTypeCount(); i++) { creaturesBorn[i] = CreaturesCount( getNormieCountInType(), // totalNormie; getNormieCountInType(), // leftNormie; getChadCountInType(), // totalChad; getChadCountInType(), // leftChadToDiscover; 1, // totalDegen; 1, // leftDegenToDiscover; getNormieCountInType(), // leftChadFarmAttempts; getChadCountInType()); // leftDegenFarmAttempts; } landCount = LandCount(getMaxLands(), getMaxLands()); allNormiesesLeft = MAX_ALL_NORMIES; eggs = _eggs; } /** * @dev Changes inventory contract */ function setInventory(address _inventory) external onlyOwner { farm.inventory = _inventory; } function reveal(uint count) external { require(_isRevelEnabled(), "Please wait for reveal enabled."); require(count > 0, "Count must be positive"); require(count <= 8, "Count must less than 9"); // random limit require( IERC20(farm.bagstoken).allowance(msg.sender, address(this)) >= count*1, "Please approve your BAGS token to this contract." ); require( IERC20(farm.bagstoken).transferFrom(msg.sender, address(this), count*1) ); uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); // random seed for 8 reveals (8x32=256) for (uint i = 0; i < count; i++) { _reveal(randomSeed); randomSeed = randomSeed / 0x100000000; // shift right 32 bits } } event Log(string mess); /** * @dev Start farming process. New NFT - Egg will minted for user * @param _creatureId - NFT tokenId, caller must be owner of this token * @param _landId -- NFT tokenId, caller must be owner of this token */ function farmDeploy(uint256 _creatureId, uint256 _landId) external { require(FARMING_ENABLED == true, "Chief Farmer not enable yet"); require(ICreatures(farm.creatures).ownerOf(_creatureId) == msg.sender, "Need to be Creature Owner" ); require(ILand(farm.land).ownerOf(_landId) == msg.sender, "Need to be Land Owner" ); (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity(_creatureId); require((DegenFarmBase.Rarity)(crRarity) == Rarity.Normie || (DegenFarmBase.Rarity)(crRarity) == Rarity.Chad, "Can farm only Normie and Chad"); //Check that farming available yet if (crRarity == 0) { require(creaturesBorn[crType].leftChadToDiscover > 0, "No more chads left"); } else { require(creaturesBorn[crType].leftDegenToDiscover > 0, "No more Degen left"); } //1. Lets make amulet price snapshot //1.1. First we need creat array with properly elements count uint256[] memory prices1 = new uint256[](amulets[crType].length); uint256[] memory prices2 = new uint256[](amulets[crType].length); prices1 = _getExistingAmuletsPrices(amulets[crType]); //2.Check and save Common Amulets price(if not exist yet) _saveCommonAmuletPrices(block.timestamp); //3. Save deploy record farming.push( FarmRecord({ creatureId: _creatureId, landId: _landId, harvestTime: block.timestamp + getFarmingDuration(), amuletsPrice1: prices1, amuletsPrice2: prices2, harvest: Result.Fail, harvestId: 0, commonAmuletInitialHold: _getCommonAmuletsHoldState(msg.sender) //save initial hold state }) ); // Let's mint Egg. eggs.mint( msg.sender, // farmer farming.length - 1 // tokenId ); //STAKE LAND and Creatures!!!! ILand(farm.land).transferFrom(msg.sender, address(this), _landId); ICreatures(farm.creatures).transferFrom(msg.sender, address(this), _creatureId); } /** * @dev Finish farming process. Egg NFT will be burn * @param _deployId - NFT tokenId, caller must be owner of this token */ function harvest(uint256 _deployId) external { require(eggs.ownerOf(_deployId) == msg.sender, "This is NOT YOUR EGG"); FarmRecord storage f = farming[_deployId]; require(f.harvestTime <= block.timestamp, "To early for harvest"); //Lets Calculate Dung/CHAD-DEGEN chance Result farmingResult; Bonus memory bonus; //1. BaseChance (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity( f.creatureId ); uint16 baseChance; if (crRarity == 0) { //Try farm CHAD. So if there is no CHADs any more we must return assets if (creaturesBorn[crType].leftChadToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftChadToDiscover * 100 /(creaturesBorn[crType].leftChadFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftChadFarmAttempts -= 1; } else { //Try farm DEGEN. So if there is no DEGENSs any more we must return assets if (creaturesBorn[crType].leftDegenToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftDegenToDiscover * 100 /(creaturesBorn[crType].leftDegenFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftDegenFarmAttempts -= 1; } ////////////////////////////////////////////// // 2. Bonus for amulet token ***HOLD*** // 3. Bonus for amulets BULLs trend ////////////////////////////////////////////// bonus.amuletHold = 0; bonus.amuletBullTrend = 0; //Check common amulets _saveCommonAmuletPrices(block.timestamp); //Get current hold stae for (uint8 i = 0; i < COMMON_AMULETS.length; i ++){ if (f.commonAmuletInitialHold[i] && _getCommonAmuletsHoldState(msg.sender)[i]) { //token was hold at deploy time and now - iT IS GOOD //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(COMMON_AMULETS[i]); bonus.amuletHold = uint16( IERC20(COMMON_AMULETS[i]).balanceOf(msg.sender) * 100 / maxAmuletBalances[COMMON_AMULETS[i]] * BONUS_POINTS_AMULET_HOLD / 100 //100 used for scale ); //Lets check Bull TREND if (_getCommonAmuletPrices(f.harvestTime - getFarmingDuration())[i] < _getCommonAmuletPrices(block.timestamp)[i] ) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } //Ok, if there is NO common amulets lets check personal uint256[] memory prices2 = new uint256[](amulets[crType].length); prices2 = _getExistingAmuletsPrices(amulets[crType]); if (bonus.amuletHold != BONUS_POINTS_AMULET_HOLD) { for (uint8 i=0; i < f.amuletsPrice1.length; i ++){ if (f.amuletsPrice1[i] > 0 && prices2[i] > 0){ //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(amulets[i][crType]); bonus.amuletHold = uint16( IERC20(amulets[i][crType]).balanceOf(msg.sender) * 100 //100 used for scale / maxAmuletBalances[amulets[i][crType]] * BONUS_POINTS_AMULET_HOLD /100 ); //Lets check Bull TREND if (f.amuletsPrice1[i] < prices2[i]) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } } ////////////////////////////////////////////// ////////////////////////////////////////////// //4. Bonus for inventory ////////////////////////////////////////////// bonus.inventoryHold = 0; if (userStakedTools[msg.sender].length > 0) { for (uint8 i=0; i<userStakedTools[msg.sender].length; i++) { if (userStakedTools[msg.sender][i] > 0){ bonus.inventoryHold = bonus.inventoryHold + IInventory(farm.inventory).getToolBoost(i); } } } ////////////////////////////////////////////// uint16 allBonus = bonus.amuletHold + bonus.amuletBullTrend + bonus.inventoryHold; uint8 chanceOfRarityUP = uint8( (baseChance + allBonus) * 100 / (100 + allBonus) ); uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = chanceOfRarityUP; choiceWeight[1] = 100 - chanceOfRarityUP; uint8 choice = uint8(_getWeightedChoice(choiceWeight)); if (choice == 0) { f.harvestId = (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId; // Mint new chad/degen uint32 index; //Decrease appropriate CREATRURE COUNT if (crRarity + 1 == uint8(Rarity.Chad)) { index = creaturesBorn[crType].totalChad - creaturesBorn[crType].leftChadToDiscover + 1; creaturesBorn[crType].leftChadToDiscover -= 1; farmingResult = Result.Chad; } else if (crRarity + 1 == uint8(Rarity.Degen)) { index = creaturesBorn[crType].totalDegen - creaturesBorn[crType].leftDegenToDiscover + 1; creaturesBorn[crType].leftDegenToDiscover -= 1; farmingResult = Result.Degen; } ICreatures(farm.creatures).mint( msg.sender, (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId, // new iD crType, //AnimalType crRarity + 1, index // index ); } else { //Mint new dung IDung(farm.dungtoken).mint(msg.sender, FARM_DUNG_AMOUNT); farmingResult = Result.Dung; } //BURN Land ILand(farm.land).burn(f.landId); _endFarming(_deployId, farmingResult); emit Harvest( _deployId, msg.sender, uint8(farmingResult), baseChance, bonus.amuletHold, bonus.amuletBullTrend, bonus.inventoryHold ); } /** * @dev Stake one inventory item * @param _itemId - NFT tokenId, caller must be owner of this token */ function stakeOneTool(uint8 _itemId) external { _stakeOneTool(_itemId); } /** * @dev UnStake one inventory item * @param _itemId - NFT tokenId */ function unstakeOneTool(uint8 _itemId) external { _unstakeOneTool(_itemId); } ///////////////////////////////////////////////////// //// Admin functions /////// ///////////////////////////////////////////////////// function setOneCommonAmulet(uint8 _index, address _token) external onlyOwner { COMMON_AMULETS[_index] = _token; } function setAmuletForOneCreature(uint8 _index, address[] memory _tokens) external onlyOwner { delete amulets[_index]; amulets[_index] = _tokens; } function setPriceProvider(address _priceProvider) external onlyOwner { priceProvider = _priceProvider; } function enableReveal(bool _isEnabled) external onlyOwner { REVEAL_ENABLED = _isEnabled; } function enableFarming(bool _isEnabled) external onlyOwner { FARMING_ENABLED = _isEnabled; } //////////////////////////////////////// /// Proxy for NFT Operators mamnage // //////////////////////////////////////// function addOperator(address _contract, address newOperator) external onlyOwner { IOperatorManage(_contract).addOperator(newOperator); } function removeOperator(address _contract, address oldOperator) external onlyOwner { IOperatorManage(_contract).removeOperator(oldOperator); } function reclaimToken(address _contract, IERC20 anyTokens, address _admin) external onlyOwner { IOperatorManage(_contract).withdrawERC20(anyTokens, _admin); } //////////////////////////////////////////////////////// function getCreatureAmulets(uint8 _creatureType) external view returns (address[] memory) { return _getCreatureAmulets(_creatureType); } function _getCreatureAmulets(uint8 _creatureType) internal view returns (address[] memory) { return amulets[_creatureType]; } function getCreatureStat(uint8 _creatureType) external view returns ( uint16, uint16, uint16, uint16, uint16, uint16, uint16, uint16 ) { CreaturesCount storage stat = creaturesBorn[_creatureType]; return ( stat.totalNormie, stat.leftNormie, stat.totalChad, stat.leftChadToDiscover, stat.totalDegen, stat.leftDegenToDiscover, stat.leftChadFarmAttempts, stat.leftDegenFarmAttempts ); } function getWeightedChoice(uint8[] memory _weights) external view returns (uint8){ return _getWeightedChoice(_weights); } function _getWeightedChoice(uint8[] memory _weights) internal view returns (uint8){ uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); return _getWeightedChoice2(_weights, randomSeed); } function getFarmingById(uint256 _farmingId) external view returns (FarmRecord memory) { return farming[_farmingId]; } function getCommonAmuletPrices(uint256 _timestamp) external view returns (uint256[3] memory) { return _getCommonAmuletPrices(_timestamp); } function getOneAmuletPrice(address _token) external view returns (uint256) { return _getOneAmuletPrice(_token); } /////////////////////////////////////////////// /// Internals /////// /////////////////////////////////////////////// /** * @dev Save farming results in storage and mint * appropriate token (NFT, ERC20 or None) */ function _endFarming(uint256 _deployId, Result _res) internal { //TODO need refactor if EGGs will be FarmRecord storage f = farming[_deployId]; f.harvest = _res; // unstake creature ICreatures(farm.creatures).transferFrom(address(this), msg.sender, f.creatureId); eggs.burn(_deployId); // Burn EGG if (_res == Result.Fail) { //unstake land (if staked) if (ILand(farm.land).ownerOf(f.landId) == address(this)){ ILand(farm.land).transferFrom(address(this), msg.sender, f.landId); } emit Harvest( _deployId, msg.sender, uint8(_res), 0, //baseChance 0, //bonus.amuletHold, 0, //bonus.amuletBullTrend, 0 //bonus.inventoryHold ); } } function _stakeOneTool(uint8 _itemId) internal { require(IInventory(farm.inventory).balanceOf(msg.sender, _itemId) >= 1, "You must own this tool for stake!" ); //Before stake we need two checks. //1. Removed //2. Cant`t stake one tool more than one item require(userStakedTools[msg.sender][_itemId] == 0, "Tool is already staked"); //stake IInventory(farm.inventory).safeTransferFrom( msg.sender, address(this), _itemId, 1, bytes('0') ); userStakedTools[msg.sender][_itemId] = block.timestamp; } function _unstakeOneTool(uint8 _itemId) internal { require(userStakedTools[msg.sender][_itemId] > 0, "This tool is not staked yet"); require(block.timestamp - userStakedTools[msg.sender][_itemId] >= getToolUnstakeDelay(), "Cant unstake earlier than a week" ); userStakedTools[msg.sender][_itemId] = 0; IInventory(farm.inventory).safeTransferFrom( address(this), msg.sender, _itemId, 1, bytes('0') ); } function _saveCommonAmuletPrices(uint256 _timestamp) internal { //Lets check if price NOT exist for this timestamp - lets save it if (commonAmuletPrices[_timestamp][0] == 0) { for (uint8 i=0; i < COMMON_AMULETS.length; i++){ commonAmuletPrices[_timestamp][i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } } } function _checkAndSaveMaxAmuletPrice(address _amulet) internal { if (IERC20(_amulet).balanceOf(msg.sender) > maxAmuletBalances[_amulet] ) { maxAmuletBalances[_amulet] = IERC20(_amulet).balanceOf(msg.sender); } } function _getCommonAmuletPrices(uint256 _timestamp) internal view returns (uint256[3] memory) { //Lets check if price allready exist for this timestamp - just return it if (commonAmuletPrices[_timestamp][0] != 0) { return commonAmuletPrices[_timestamp]; } //If price is not exist lets get it from oracles uint256[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ res[i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } return res; } function _getCommonAmuletsHoldState(address _farmer) internal view returns (bool[3] memory) { //If token balance =0 - set false bool[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ if (IERC20(COMMON_AMULETS[i]).balanceOf(_farmer) > 0){ res[i] = true; } else { // Set to zero if token balance is 0 res[i] = false; } } return res; } function _getExistingAmuletsPrices(address[] memory _tokens) internal view returns (uint256[] memory) { uint256[] memory res = new uint256[](_tokens.length); for (uint8 i=0; i < _tokens.length; i++){ if (IERC20(_tokens[i]).balanceOf(msg.sender) > 0){ res[i] = _getOneAmuletPrice(_tokens[i]); } else { // Set to zero if token balance is 0 res[i] = 0; } } return res; } function _getOneAmuletPrice(address _token) internal view returns (uint256) { return IAmuletPriceProvider(priceProvider).getLastPrice(_token); } function _isRevelEnabled() internal view returns (bool) { return REVEAL_ENABLED; } function _reveal(uint randomSeed) internal { require ((landCount.left + allNormiesesLeft) > 0, "Sorry, no more reveal!"); //1. Lets choose Land OR Creature, % //So we have two possible results. 1 - Land, 0 - Creature. // sum of weights = 100, lets define weigth for Creature uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = uint8( uint32(allNormiesesLeft) * CREATURE_P_MULT // * 100 removed due CREATURE_P_MULT / (CREATURE_P_MULT * uint32(allNormiesesLeft) / 100 + uint32(landCount.left)) ); choiceWeight[1] = 100 - choiceWeight[0]; uint8 choice = uint8(_getWeightedChoice2(choiceWeight, randomSeed)); //Check that choice can be executed if (choice != 0 && landCount.left == 0) { //There are no more Lands. So we need change choice choice = 0; } if (choice == 0) { // create creature uint8[] memory choiceWeight0 = new uint8[](getCreatureTypeCount()); //2. Ok, Creature will be born. But what kind of? for (uint8 i = 0; i < getCreatureTypeCount(); i ++) { choiceWeight0[i] = uint8(creaturesBorn[i].leftNormie); } choice = uint8(_getWeightedChoice2(choiceWeight0, randomSeed / 0x10000)); // shift right 16 bits ICreatures(farm.creatures).mint( msg.sender, MAX_ALL_NORMIES - allNormiesesLeft, choice, //AnimalType 0, creaturesBorn[choice].totalNormie - creaturesBorn[choice].leftNormie + 1 // index ); emit Reveal(MAX_ALL_NORMIES - allNormiesesLeft, true, choice); allNormiesesLeft -= 1; creaturesBorn[choice].leftNormie -= 1; } else { // create land ILand(farm.land).mint( msg.sender, getMaxLands() - landCount.left ); emit Reveal(getMaxLands() - landCount.left , false, 0); landCount.left -= 1; } } function _getWeightedChoice2(uint8[] memory _weights, uint randomSeed) internal view returns (uint8){ uint256 sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { sum_of_weights += _weights[i]; } uint256 rnd = randomSeed % sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { if (rnd < _weights[i]) { return i; } rnd -= _weights[i]; } return 0; } /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); } /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)")); } function getCreatureTypeCount() virtual internal view returns (uint16); function getFarmingDuration() virtual internal view returns (uint); function getToolUnstakeDelay() virtual internal view returns (uint); function getNormieCountInType() virtual internal view returns (uint16); function getChadCountInType() virtual internal view returns (uint16); function getMaxLands() virtual internal view returns (uint16); function getUsersTokens(address _owner) external view returns (uint256[] memory) { return eggs.getUsersTokens(_owner); } }
addOperator
function addOperator(address _contract, address newOperator) external onlyOwner { IOperatorManage(_contract).addOperator(newOperator); }
//////////////////////////////////////// /// Proxy for NFT Operators mamnage // ////////////////////////////////////////
NatSpecSingleLine
v0.7.4+commit.3f05b770
MIT
ipfs://308c7d0f38216f626771d86f2b5b3091893bd5f12659a801a1f13db0060ec78f
{ "func_code_index": [ 17158, 17314 ] }
3,316
Creatures
DegensFarmBase.sol
0xd227df494367a8b769b4bf2bbebd0388a8758741
Solidity
DegenFarmBase
abstract contract DegenFarmBase is ERC1155Receiver, Ownable { enum AnimalType { Cow, Horse, Rabbit, Chicken, Pig, Cat, Dog, Goose, Goat, Sheep, Snake, Fish, Frog, Worm, Lama, Mouse, Camel, Donkey, Bee, Duck, GenesisEgg // 20 } enum Rarity { Normie, // 0 Chad, // 1 Degen, // 2 Unique // 3 } enum Result {Fail, Dung, Chad, Degen} //External conatrct addresses used with this farm. struct AddressRegistry { address land; address creatures; address inventory; address bagstoken; address dungtoken; } //Degens Farm Key numbers struct CreaturesCount { uint16 totalNormie; uint16 leftNormie; uint16 totalChad; uint16 leftChadToDiscover; uint16 totalDegen; uint16 leftDegenToDiscover; uint16 leftChadFarmAttempts; uint16 leftDegenFarmAttempts; } //Land count record struct LandCount { uint16 total; uint16 left; } // Record represent one farming act struct FarmRecord { uint256 creatureId; uint256 landId; uint256 harvestTime; uint256[] amuletsPrice1; uint256[] amuletsPrice2; Result harvest; uint256 harvestId; //new NFT tokenId bool[3] commonAmuletInitialHold; } // Bonus for better harvest struct Bonus { uint16 amuletHold; uint16 amuletBullTrend; uint16 inventoryHold; } uint8 constant public CREATURE_TYPE_COUNT_MAX = 20; //how much creatures types may be used //Creature probubility multiplier, scaled with 100. 3.00 - 300, 3.05 - 305 etc // so we need additional divide on 100 in formula uint32 constant public CREATURE_P_MULT = 230; uint16 public MAX_ALL_NORMIES = getCreatureTypeCount() * getNormieCountInType(); //subj uint256 constant public NFT_ID_MULTIPLIER = 10000; //must be set more then all Normies count uint256 constant public FARM_DUNG_AMOUNT = 250e32; //per one harvest uint16 constant public BONUS_POINTS_AMULET_HOLD = 10; uint16 constant public BONUS_POINTS_AMULET_BULL_TREND = 90; //Common Amulet addresses address[3] public COMMON_AMULETS = [ 0xa0246c9032bC3A600820415aE600c6388619A14D, 0x87d73E916D7057945c9BcD8cdd94e42A6F47f776, 0x126c121f99e1E211dF2e5f8De2d96Fa36647c855 ]; bool public REVEAL_ENABLED = false; bool public FARMING_ENABLED = false; address public priceProvider; IEggs public eggs; address[][CREATURE_TYPE_COUNT_MAX] public amulets; //amulets for creatures AddressRegistry public farm; LandCount public landCount; //common token price snapshots mapping(uint256 => uint256[3]) public commonAmuletPrices; mapping(address => uint256) public maxAmuletBalances; // mapping from user to his(her) staked tools // Index of uint256[6] represent tool NFT itemID mapping(address => uint256[6]) public userStakedTools; uint16 public allNormiesesLeft; CreaturesCount[CREATURE_TYPE_COUNT_MAX] public creaturesBorn; FarmRecord[] farming; event Reveal(uint256 indexed _tokenId, bool _isCreature, uint8 _animalType); event Harvest( uint256 indexed _eggId, address farmer, uint8 result , uint16 baseChance, uint16 amuletHold, uint16 amuletBullTrend, uint16 inventoryHold ); constructor ( address _land, address _creatures, address _inventory, address _bagstoken, address _dungtoken, IEggs _eggs ) { farm.land = _land; farm.creatures = _creatures; farm.inventory = _inventory; farm.bagstoken = _bagstoken; farm.dungtoken = _dungtoken; // Index of creaturesBorn in this initial setting // must NOT exceed CREATURE_TYPE_COUNT for (uint i = 0; i < getCreatureTypeCount(); i++) { creaturesBorn[i] = CreaturesCount( getNormieCountInType(), // totalNormie; getNormieCountInType(), // leftNormie; getChadCountInType(), // totalChad; getChadCountInType(), // leftChadToDiscover; 1, // totalDegen; 1, // leftDegenToDiscover; getNormieCountInType(), // leftChadFarmAttempts; getChadCountInType()); // leftDegenFarmAttempts; } landCount = LandCount(getMaxLands(), getMaxLands()); allNormiesesLeft = MAX_ALL_NORMIES; eggs = _eggs; } /** * @dev Changes inventory contract */ function setInventory(address _inventory) external onlyOwner { farm.inventory = _inventory; } function reveal(uint count) external { require(_isRevelEnabled(), "Please wait for reveal enabled."); require(count > 0, "Count must be positive"); require(count <= 8, "Count must less than 9"); // random limit require( IERC20(farm.bagstoken).allowance(msg.sender, address(this)) >= count*1, "Please approve your BAGS token to this contract." ); require( IERC20(farm.bagstoken).transferFrom(msg.sender, address(this), count*1) ); uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); // random seed for 8 reveals (8x32=256) for (uint i = 0; i < count; i++) { _reveal(randomSeed); randomSeed = randomSeed / 0x100000000; // shift right 32 bits } } event Log(string mess); /** * @dev Start farming process. New NFT - Egg will minted for user * @param _creatureId - NFT tokenId, caller must be owner of this token * @param _landId -- NFT tokenId, caller must be owner of this token */ function farmDeploy(uint256 _creatureId, uint256 _landId) external { require(FARMING_ENABLED == true, "Chief Farmer not enable yet"); require(ICreatures(farm.creatures).ownerOf(_creatureId) == msg.sender, "Need to be Creature Owner" ); require(ILand(farm.land).ownerOf(_landId) == msg.sender, "Need to be Land Owner" ); (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity(_creatureId); require((DegenFarmBase.Rarity)(crRarity) == Rarity.Normie || (DegenFarmBase.Rarity)(crRarity) == Rarity.Chad, "Can farm only Normie and Chad"); //Check that farming available yet if (crRarity == 0) { require(creaturesBorn[crType].leftChadToDiscover > 0, "No more chads left"); } else { require(creaturesBorn[crType].leftDegenToDiscover > 0, "No more Degen left"); } //1. Lets make amulet price snapshot //1.1. First we need creat array with properly elements count uint256[] memory prices1 = new uint256[](amulets[crType].length); uint256[] memory prices2 = new uint256[](amulets[crType].length); prices1 = _getExistingAmuletsPrices(amulets[crType]); //2.Check and save Common Amulets price(if not exist yet) _saveCommonAmuletPrices(block.timestamp); //3. Save deploy record farming.push( FarmRecord({ creatureId: _creatureId, landId: _landId, harvestTime: block.timestamp + getFarmingDuration(), amuletsPrice1: prices1, amuletsPrice2: prices2, harvest: Result.Fail, harvestId: 0, commonAmuletInitialHold: _getCommonAmuletsHoldState(msg.sender) //save initial hold state }) ); // Let's mint Egg. eggs.mint( msg.sender, // farmer farming.length - 1 // tokenId ); //STAKE LAND and Creatures!!!! ILand(farm.land).transferFrom(msg.sender, address(this), _landId); ICreatures(farm.creatures).transferFrom(msg.sender, address(this), _creatureId); } /** * @dev Finish farming process. Egg NFT will be burn * @param _deployId - NFT tokenId, caller must be owner of this token */ function harvest(uint256 _deployId) external { require(eggs.ownerOf(_deployId) == msg.sender, "This is NOT YOUR EGG"); FarmRecord storage f = farming[_deployId]; require(f.harvestTime <= block.timestamp, "To early for harvest"); //Lets Calculate Dung/CHAD-DEGEN chance Result farmingResult; Bonus memory bonus; //1. BaseChance (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity( f.creatureId ); uint16 baseChance; if (crRarity == 0) { //Try farm CHAD. So if there is no CHADs any more we must return assets if (creaturesBorn[crType].leftChadToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftChadToDiscover * 100 /(creaturesBorn[crType].leftChadFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftChadFarmAttempts -= 1; } else { //Try farm DEGEN. So if there is no DEGENSs any more we must return assets if (creaturesBorn[crType].leftDegenToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftDegenToDiscover * 100 /(creaturesBorn[crType].leftDegenFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftDegenFarmAttempts -= 1; } ////////////////////////////////////////////// // 2. Bonus for amulet token ***HOLD*** // 3. Bonus for amulets BULLs trend ////////////////////////////////////////////// bonus.amuletHold = 0; bonus.amuletBullTrend = 0; //Check common amulets _saveCommonAmuletPrices(block.timestamp); //Get current hold stae for (uint8 i = 0; i < COMMON_AMULETS.length; i ++){ if (f.commonAmuletInitialHold[i] && _getCommonAmuletsHoldState(msg.sender)[i]) { //token was hold at deploy time and now - iT IS GOOD //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(COMMON_AMULETS[i]); bonus.amuletHold = uint16( IERC20(COMMON_AMULETS[i]).balanceOf(msg.sender) * 100 / maxAmuletBalances[COMMON_AMULETS[i]] * BONUS_POINTS_AMULET_HOLD / 100 //100 used for scale ); //Lets check Bull TREND if (_getCommonAmuletPrices(f.harvestTime - getFarmingDuration())[i] < _getCommonAmuletPrices(block.timestamp)[i] ) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } //Ok, if there is NO common amulets lets check personal uint256[] memory prices2 = new uint256[](amulets[crType].length); prices2 = _getExistingAmuletsPrices(amulets[crType]); if (bonus.amuletHold != BONUS_POINTS_AMULET_HOLD) { for (uint8 i=0; i < f.amuletsPrice1.length; i ++){ if (f.amuletsPrice1[i] > 0 && prices2[i] > 0){ //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(amulets[i][crType]); bonus.amuletHold = uint16( IERC20(amulets[i][crType]).balanceOf(msg.sender) * 100 //100 used for scale / maxAmuletBalances[amulets[i][crType]] * BONUS_POINTS_AMULET_HOLD /100 ); //Lets check Bull TREND if (f.amuletsPrice1[i] < prices2[i]) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } } ////////////////////////////////////////////// ////////////////////////////////////////////// //4. Bonus for inventory ////////////////////////////////////////////// bonus.inventoryHold = 0; if (userStakedTools[msg.sender].length > 0) { for (uint8 i=0; i<userStakedTools[msg.sender].length; i++) { if (userStakedTools[msg.sender][i] > 0){ bonus.inventoryHold = bonus.inventoryHold + IInventory(farm.inventory).getToolBoost(i); } } } ////////////////////////////////////////////// uint16 allBonus = bonus.amuletHold + bonus.amuletBullTrend + bonus.inventoryHold; uint8 chanceOfRarityUP = uint8( (baseChance + allBonus) * 100 / (100 + allBonus) ); uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = chanceOfRarityUP; choiceWeight[1] = 100 - chanceOfRarityUP; uint8 choice = uint8(_getWeightedChoice(choiceWeight)); if (choice == 0) { f.harvestId = (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId; // Mint new chad/degen uint32 index; //Decrease appropriate CREATRURE COUNT if (crRarity + 1 == uint8(Rarity.Chad)) { index = creaturesBorn[crType].totalChad - creaturesBorn[crType].leftChadToDiscover + 1; creaturesBorn[crType].leftChadToDiscover -= 1; farmingResult = Result.Chad; } else if (crRarity + 1 == uint8(Rarity.Degen)) { index = creaturesBorn[crType].totalDegen - creaturesBorn[crType].leftDegenToDiscover + 1; creaturesBorn[crType].leftDegenToDiscover -= 1; farmingResult = Result.Degen; } ICreatures(farm.creatures).mint( msg.sender, (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId, // new iD crType, //AnimalType crRarity + 1, index // index ); } else { //Mint new dung IDung(farm.dungtoken).mint(msg.sender, FARM_DUNG_AMOUNT); farmingResult = Result.Dung; } //BURN Land ILand(farm.land).burn(f.landId); _endFarming(_deployId, farmingResult); emit Harvest( _deployId, msg.sender, uint8(farmingResult), baseChance, bonus.amuletHold, bonus.amuletBullTrend, bonus.inventoryHold ); } /** * @dev Stake one inventory item * @param _itemId - NFT tokenId, caller must be owner of this token */ function stakeOneTool(uint8 _itemId) external { _stakeOneTool(_itemId); } /** * @dev UnStake one inventory item * @param _itemId - NFT tokenId */ function unstakeOneTool(uint8 _itemId) external { _unstakeOneTool(_itemId); } ///////////////////////////////////////////////////// //// Admin functions /////// ///////////////////////////////////////////////////// function setOneCommonAmulet(uint8 _index, address _token) external onlyOwner { COMMON_AMULETS[_index] = _token; } function setAmuletForOneCreature(uint8 _index, address[] memory _tokens) external onlyOwner { delete amulets[_index]; amulets[_index] = _tokens; } function setPriceProvider(address _priceProvider) external onlyOwner { priceProvider = _priceProvider; } function enableReveal(bool _isEnabled) external onlyOwner { REVEAL_ENABLED = _isEnabled; } function enableFarming(bool _isEnabled) external onlyOwner { FARMING_ENABLED = _isEnabled; } //////////////////////////////////////// /// Proxy for NFT Operators mamnage // //////////////////////////////////////// function addOperator(address _contract, address newOperator) external onlyOwner { IOperatorManage(_contract).addOperator(newOperator); } function removeOperator(address _contract, address oldOperator) external onlyOwner { IOperatorManage(_contract).removeOperator(oldOperator); } function reclaimToken(address _contract, IERC20 anyTokens, address _admin) external onlyOwner { IOperatorManage(_contract).withdrawERC20(anyTokens, _admin); } //////////////////////////////////////////////////////// function getCreatureAmulets(uint8 _creatureType) external view returns (address[] memory) { return _getCreatureAmulets(_creatureType); } function _getCreatureAmulets(uint8 _creatureType) internal view returns (address[] memory) { return amulets[_creatureType]; } function getCreatureStat(uint8 _creatureType) external view returns ( uint16, uint16, uint16, uint16, uint16, uint16, uint16, uint16 ) { CreaturesCount storage stat = creaturesBorn[_creatureType]; return ( stat.totalNormie, stat.leftNormie, stat.totalChad, stat.leftChadToDiscover, stat.totalDegen, stat.leftDegenToDiscover, stat.leftChadFarmAttempts, stat.leftDegenFarmAttempts ); } function getWeightedChoice(uint8[] memory _weights) external view returns (uint8){ return _getWeightedChoice(_weights); } function _getWeightedChoice(uint8[] memory _weights) internal view returns (uint8){ uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); return _getWeightedChoice2(_weights, randomSeed); } function getFarmingById(uint256 _farmingId) external view returns (FarmRecord memory) { return farming[_farmingId]; } function getCommonAmuletPrices(uint256 _timestamp) external view returns (uint256[3] memory) { return _getCommonAmuletPrices(_timestamp); } function getOneAmuletPrice(address _token) external view returns (uint256) { return _getOneAmuletPrice(_token); } /////////////////////////////////////////////// /// Internals /////// /////////////////////////////////////////////// /** * @dev Save farming results in storage and mint * appropriate token (NFT, ERC20 or None) */ function _endFarming(uint256 _deployId, Result _res) internal { //TODO need refactor if EGGs will be FarmRecord storage f = farming[_deployId]; f.harvest = _res; // unstake creature ICreatures(farm.creatures).transferFrom(address(this), msg.sender, f.creatureId); eggs.burn(_deployId); // Burn EGG if (_res == Result.Fail) { //unstake land (if staked) if (ILand(farm.land).ownerOf(f.landId) == address(this)){ ILand(farm.land).transferFrom(address(this), msg.sender, f.landId); } emit Harvest( _deployId, msg.sender, uint8(_res), 0, //baseChance 0, //bonus.amuletHold, 0, //bonus.amuletBullTrend, 0 //bonus.inventoryHold ); } } function _stakeOneTool(uint8 _itemId) internal { require(IInventory(farm.inventory).balanceOf(msg.sender, _itemId) >= 1, "You must own this tool for stake!" ); //Before stake we need two checks. //1. Removed //2. Cant`t stake one tool more than one item require(userStakedTools[msg.sender][_itemId] == 0, "Tool is already staked"); //stake IInventory(farm.inventory).safeTransferFrom( msg.sender, address(this), _itemId, 1, bytes('0') ); userStakedTools[msg.sender][_itemId] = block.timestamp; } function _unstakeOneTool(uint8 _itemId) internal { require(userStakedTools[msg.sender][_itemId] > 0, "This tool is not staked yet"); require(block.timestamp - userStakedTools[msg.sender][_itemId] >= getToolUnstakeDelay(), "Cant unstake earlier than a week" ); userStakedTools[msg.sender][_itemId] = 0; IInventory(farm.inventory).safeTransferFrom( address(this), msg.sender, _itemId, 1, bytes('0') ); } function _saveCommonAmuletPrices(uint256 _timestamp) internal { //Lets check if price NOT exist for this timestamp - lets save it if (commonAmuletPrices[_timestamp][0] == 0) { for (uint8 i=0; i < COMMON_AMULETS.length; i++){ commonAmuletPrices[_timestamp][i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } } } function _checkAndSaveMaxAmuletPrice(address _amulet) internal { if (IERC20(_amulet).balanceOf(msg.sender) > maxAmuletBalances[_amulet] ) { maxAmuletBalances[_amulet] = IERC20(_amulet).balanceOf(msg.sender); } } function _getCommonAmuletPrices(uint256 _timestamp) internal view returns (uint256[3] memory) { //Lets check if price allready exist for this timestamp - just return it if (commonAmuletPrices[_timestamp][0] != 0) { return commonAmuletPrices[_timestamp]; } //If price is not exist lets get it from oracles uint256[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ res[i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } return res; } function _getCommonAmuletsHoldState(address _farmer) internal view returns (bool[3] memory) { //If token balance =0 - set false bool[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ if (IERC20(COMMON_AMULETS[i]).balanceOf(_farmer) > 0){ res[i] = true; } else { // Set to zero if token balance is 0 res[i] = false; } } return res; } function _getExistingAmuletsPrices(address[] memory _tokens) internal view returns (uint256[] memory) { uint256[] memory res = new uint256[](_tokens.length); for (uint8 i=0; i < _tokens.length; i++){ if (IERC20(_tokens[i]).balanceOf(msg.sender) > 0){ res[i] = _getOneAmuletPrice(_tokens[i]); } else { // Set to zero if token balance is 0 res[i] = 0; } } return res; } function _getOneAmuletPrice(address _token) internal view returns (uint256) { return IAmuletPriceProvider(priceProvider).getLastPrice(_token); } function _isRevelEnabled() internal view returns (bool) { return REVEAL_ENABLED; } function _reveal(uint randomSeed) internal { require ((landCount.left + allNormiesesLeft) > 0, "Sorry, no more reveal!"); //1. Lets choose Land OR Creature, % //So we have two possible results. 1 - Land, 0 - Creature. // sum of weights = 100, lets define weigth for Creature uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = uint8( uint32(allNormiesesLeft) * CREATURE_P_MULT // * 100 removed due CREATURE_P_MULT / (CREATURE_P_MULT * uint32(allNormiesesLeft) / 100 + uint32(landCount.left)) ); choiceWeight[1] = 100 - choiceWeight[0]; uint8 choice = uint8(_getWeightedChoice2(choiceWeight, randomSeed)); //Check that choice can be executed if (choice != 0 && landCount.left == 0) { //There are no more Lands. So we need change choice choice = 0; } if (choice == 0) { // create creature uint8[] memory choiceWeight0 = new uint8[](getCreatureTypeCount()); //2. Ok, Creature will be born. But what kind of? for (uint8 i = 0; i < getCreatureTypeCount(); i ++) { choiceWeight0[i] = uint8(creaturesBorn[i].leftNormie); } choice = uint8(_getWeightedChoice2(choiceWeight0, randomSeed / 0x10000)); // shift right 16 bits ICreatures(farm.creatures).mint( msg.sender, MAX_ALL_NORMIES - allNormiesesLeft, choice, //AnimalType 0, creaturesBorn[choice].totalNormie - creaturesBorn[choice].leftNormie + 1 // index ); emit Reveal(MAX_ALL_NORMIES - allNormiesesLeft, true, choice); allNormiesesLeft -= 1; creaturesBorn[choice].leftNormie -= 1; } else { // create land ILand(farm.land).mint( msg.sender, getMaxLands() - landCount.left ); emit Reveal(getMaxLands() - landCount.left , false, 0); landCount.left -= 1; } } function _getWeightedChoice2(uint8[] memory _weights, uint randomSeed) internal view returns (uint8){ uint256 sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { sum_of_weights += _weights[i]; } uint256 rnd = randomSeed % sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { if (rnd < _weights[i]) { return i; } rnd -= _weights[i]; } return 0; } /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); } /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)")); } function getCreatureTypeCount() virtual internal view returns (uint16); function getFarmingDuration() virtual internal view returns (uint); function getToolUnstakeDelay() virtual internal view returns (uint); function getNormieCountInType() virtual internal view returns (uint16); function getChadCountInType() virtual internal view returns (uint16); function getMaxLands() virtual internal view returns (uint16); function getUsersTokens(address _owner) external view returns (uint256[] memory) { return eggs.getUsersTokens(_owner); } }
getCreatureAmulets
function getCreatureAmulets(uint8 _creatureType) external view returns (address[] memory) { return _getCreatureAmulets(_creatureType); }
////////////////////////////////////////////////////////
NatSpecSingleLine
v0.7.4+commit.3f05b770
MIT
ipfs://308c7d0f38216f626771d86f2b5b3091893bd5f12659a801a1f13db0060ec78f
{ "func_code_index": [ 17724, 17879 ] }
3,317
Creatures
DegensFarmBase.sol
0xd227df494367a8b769b4bf2bbebd0388a8758741
Solidity
DegenFarmBase
abstract contract DegenFarmBase is ERC1155Receiver, Ownable { enum AnimalType { Cow, Horse, Rabbit, Chicken, Pig, Cat, Dog, Goose, Goat, Sheep, Snake, Fish, Frog, Worm, Lama, Mouse, Camel, Donkey, Bee, Duck, GenesisEgg // 20 } enum Rarity { Normie, // 0 Chad, // 1 Degen, // 2 Unique // 3 } enum Result {Fail, Dung, Chad, Degen} //External conatrct addresses used with this farm. struct AddressRegistry { address land; address creatures; address inventory; address bagstoken; address dungtoken; } //Degens Farm Key numbers struct CreaturesCount { uint16 totalNormie; uint16 leftNormie; uint16 totalChad; uint16 leftChadToDiscover; uint16 totalDegen; uint16 leftDegenToDiscover; uint16 leftChadFarmAttempts; uint16 leftDegenFarmAttempts; } //Land count record struct LandCount { uint16 total; uint16 left; } // Record represent one farming act struct FarmRecord { uint256 creatureId; uint256 landId; uint256 harvestTime; uint256[] amuletsPrice1; uint256[] amuletsPrice2; Result harvest; uint256 harvestId; //new NFT tokenId bool[3] commonAmuletInitialHold; } // Bonus for better harvest struct Bonus { uint16 amuletHold; uint16 amuletBullTrend; uint16 inventoryHold; } uint8 constant public CREATURE_TYPE_COUNT_MAX = 20; //how much creatures types may be used //Creature probubility multiplier, scaled with 100. 3.00 - 300, 3.05 - 305 etc // so we need additional divide on 100 in formula uint32 constant public CREATURE_P_MULT = 230; uint16 public MAX_ALL_NORMIES = getCreatureTypeCount() * getNormieCountInType(); //subj uint256 constant public NFT_ID_MULTIPLIER = 10000; //must be set more then all Normies count uint256 constant public FARM_DUNG_AMOUNT = 250e32; //per one harvest uint16 constant public BONUS_POINTS_AMULET_HOLD = 10; uint16 constant public BONUS_POINTS_AMULET_BULL_TREND = 90; //Common Amulet addresses address[3] public COMMON_AMULETS = [ 0xa0246c9032bC3A600820415aE600c6388619A14D, 0x87d73E916D7057945c9BcD8cdd94e42A6F47f776, 0x126c121f99e1E211dF2e5f8De2d96Fa36647c855 ]; bool public REVEAL_ENABLED = false; bool public FARMING_ENABLED = false; address public priceProvider; IEggs public eggs; address[][CREATURE_TYPE_COUNT_MAX] public amulets; //amulets for creatures AddressRegistry public farm; LandCount public landCount; //common token price snapshots mapping(uint256 => uint256[3]) public commonAmuletPrices; mapping(address => uint256) public maxAmuletBalances; // mapping from user to his(her) staked tools // Index of uint256[6] represent tool NFT itemID mapping(address => uint256[6]) public userStakedTools; uint16 public allNormiesesLeft; CreaturesCount[CREATURE_TYPE_COUNT_MAX] public creaturesBorn; FarmRecord[] farming; event Reveal(uint256 indexed _tokenId, bool _isCreature, uint8 _animalType); event Harvest( uint256 indexed _eggId, address farmer, uint8 result , uint16 baseChance, uint16 amuletHold, uint16 amuletBullTrend, uint16 inventoryHold ); constructor ( address _land, address _creatures, address _inventory, address _bagstoken, address _dungtoken, IEggs _eggs ) { farm.land = _land; farm.creatures = _creatures; farm.inventory = _inventory; farm.bagstoken = _bagstoken; farm.dungtoken = _dungtoken; // Index of creaturesBorn in this initial setting // must NOT exceed CREATURE_TYPE_COUNT for (uint i = 0; i < getCreatureTypeCount(); i++) { creaturesBorn[i] = CreaturesCount( getNormieCountInType(), // totalNormie; getNormieCountInType(), // leftNormie; getChadCountInType(), // totalChad; getChadCountInType(), // leftChadToDiscover; 1, // totalDegen; 1, // leftDegenToDiscover; getNormieCountInType(), // leftChadFarmAttempts; getChadCountInType()); // leftDegenFarmAttempts; } landCount = LandCount(getMaxLands(), getMaxLands()); allNormiesesLeft = MAX_ALL_NORMIES; eggs = _eggs; } /** * @dev Changes inventory contract */ function setInventory(address _inventory) external onlyOwner { farm.inventory = _inventory; } function reveal(uint count) external { require(_isRevelEnabled(), "Please wait for reveal enabled."); require(count > 0, "Count must be positive"); require(count <= 8, "Count must less than 9"); // random limit require( IERC20(farm.bagstoken).allowance(msg.sender, address(this)) >= count*1, "Please approve your BAGS token to this contract." ); require( IERC20(farm.bagstoken).transferFrom(msg.sender, address(this), count*1) ); uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); // random seed for 8 reveals (8x32=256) for (uint i = 0; i < count; i++) { _reveal(randomSeed); randomSeed = randomSeed / 0x100000000; // shift right 32 bits } } event Log(string mess); /** * @dev Start farming process. New NFT - Egg will minted for user * @param _creatureId - NFT tokenId, caller must be owner of this token * @param _landId -- NFT tokenId, caller must be owner of this token */ function farmDeploy(uint256 _creatureId, uint256 _landId) external { require(FARMING_ENABLED == true, "Chief Farmer not enable yet"); require(ICreatures(farm.creatures).ownerOf(_creatureId) == msg.sender, "Need to be Creature Owner" ); require(ILand(farm.land).ownerOf(_landId) == msg.sender, "Need to be Land Owner" ); (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity(_creatureId); require((DegenFarmBase.Rarity)(crRarity) == Rarity.Normie || (DegenFarmBase.Rarity)(crRarity) == Rarity.Chad, "Can farm only Normie and Chad"); //Check that farming available yet if (crRarity == 0) { require(creaturesBorn[crType].leftChadToDiscover > 0, "No more chads left"); } else { require(creaturesBorn[crType].leftDegenToDiscover > 0, "No more Degen left"); } //1. Lets make amulet price snapshot //1.1. First we need creat array with properly elements count uint256[] memory prices1 = new uint256[](amulets[crType].length); uint256[] memory prices2 = new uint256[](amulets[crType].length); prices1 = _getExistingAmuletsPrices(amulets[crType]); //2.Check and save Common Amulets price(if not exist yet) _saveCommonAmuletPrices(block.timestamp); //3. Save deploy record farming.push( FarmRecord({ creatureId: _creatureId, landId: _landId, harvestTime: block.timestamp + getFarmingDuration(), amuletsPrice1: prices1, amuletsPrice2: prices2, harvest: Result.Fail, harvestId: 0, commonAmuletInitialHold: _getCommonAmuletsHoldState(msg.sender) //save initial hold state }) ); // Let's mint Egg. eggs.mint( msg.sender, // farmer farming.length - 1 // tokenId ); //STAKE LAND and Creatures!!!! ILand(farm.land).transferFrom(msg.sender, address(this), _landId); ICreatures(farm.creatures).transferFrom(msg.sender, address(this), _creatureId); } /** * @dev Finish farming process. Egg NFT will be burn * @param _deployId - NFT tokenId, caller must be owner of this token */ function harvest(uint256 _deployId) external { require(eggs.ownerOf(_deployId) == msg.sender, "This is NOT YOUR EGG"); FarmRecord storage f = farming[_deployId]; require(f.harvestTime <= block.timestamp, "To early for harvest"); //Lets Calculate Dung/CHAD-DEGEN chance Result farmingResult; Bonus memory bonus; //1. BaseChance (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity( f.creatureId ); uint16 baseChance; if (crRarity == 0) { //Try farm CHAD. So if there is no CHADs any more we must return assets if (creaturesBorn[crType].leftChadToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftChadToDiscover * 100 /(creaturesBorn[crType].leftChadFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftChadFarmAttempts -= 1; } else { //Try farm DEGEN. So if there is no DEGENSs any more we must return assets if (creaturesBorn[crType].leftDegenToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftDegenToDiscover * 100 /(creaturesBorn[crType].leftDegenFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftDegenFarmAttempts -= 1; } ////////////////////////////////////////////// // 2. Bonus for amulet token ***HOLD*** // 3. Bonus for amulets BULLs trend ////////////////////////////////////////////// bonus.amuletHold = 0; bonus.amuletBullTrend = 0; //Check common amulets _saveCommonAmuletPrices(block.timestamp); //Get current hold stae for (uint8 i = 0; i < COMMON_AMULETS.length; i ++){ if (f.commonAmuletInitialHold[i] && _getCommonAmuletsHoldState(msg.sender)[i]) { //token was hold at deploy time and now - iT IS GOOD //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(COMMON_AMULETS[i]); bonus.amuletHold = uint16( IERC20(COMMON_AMULETS[i]).balanceOf(msg.sender) * 100 / maxAmuletBalances[COMMON_AMULETS[i]] * BONUS_POINTS_AMULET_HOLD / 100 //100 used for scale ); //Lets check Bull TREND if (_getCommonAmuletPrices(f.harvestTime - getFarmingDuration())[i] < _getCommonAmuletPrices(block.timestamp)[i] ) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } //Ok, if there is NO common amulets lets check personal uint256[] memory prices2 = new uint256[](amulets[crType].length); prices2 = _getExistingAmuletsPrices(amulets[crType]); if (bonus.amuletHold != BONUS_POINTS_AMULET_HOLD) { for (uint8 i=0; i < f.amuletsPrice1.length; i ++){ if (f.amuletsPrice1[i] > 0 && prices2[i] > 0){ //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(amulets[i][crType]); bonus.amuletHold = uint16( IERC20(amulets[i][crType]).balanceOf(msg.sender) * 100 //100 used for scale / maxAmuletBalances[amulets[i][crType]] * BONUS_POINTS_AMULET_HOLD /100 ); //Lets check Bull TREND if (f.amuletsPrice1[i] < prices2[i]) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } } ////////////////////////////////////////////// ////////////////////////////////////////////// //4. Bonus for inventory ////////////////////////////////////////////// bonus.inventoryHold = 0; if (userStakedTools[msg.sender].length > 0) { for (uint8 i=0; i<userStakedTools[msg.sender].length; i++) { if (userStakedTools[msg.sender][i] > 0){ bonus.inventoryHold = bonus.inventoryHold + IInventory(farm.inventory).getToolBoost(i); } } } ////////////////////////////////////////////// uint16 allBonus = bonus.amuletHold + bonus.amuletBullTrend + bonus.inventoryHold; uint8 chanceOfRarityUP = uint8( (baseChance + allBonus) * 100 / (100 + allBonus) ); uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = chanceOfRarityUP; choiceWeight[1] = 100 - chanceOfRarityUP; uint8 choice = uint8(_getWeightedChoice(choiceWeight)); if (choice == 0) { f.harvestId = (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId; // Mint new chad/degen uint32 index; //Decrease appropriate CREATRURE COUNT if (crRarity + 1 == uint8(Rarity.Chad)) { index = creaturesBorn[crType].totalChad - creaturesBorn[crType].leftChadToDiscover + 1; creaturesBorn[crType].leftChadToDiscover -= 1; farmingResult = Result.Chad; } else if (crRarity + 1 == uint8(Rarity.Degen)) { index = creaturesBorn[crType].totalDegen - creaturesBorn[crType].leftDegenToDiscover + 1; creaturesBorn[crType].leftDegenToDiscover -= 1; farmingResult = Result.Degen; } ICreatures(farm.creatures).mint( msg.sender, (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId, // new iD crType, //AnimalType crRarity + 1, index // index ); } else { //Mint new dung IDung(farm.dungtoken).mint(msg.sender, FARM_DUNG_AMOUNT); farmingResult = Result.Dung; } //BURN Land ILand(farm.land).burn(f.landId); _endFarming(_deployId, farmingResult); emit Harvest( _deployId, msg.sender, uint8(farmingResult), baseChance, bonus.amuletHold, bonus.amuletBullTrend, bonus.inventoryHold ); } /** * @dev Stake one inventory item * @param _itemId - NFT tokenId, caller must be owner of this token */ function stakeOneTool(uint8 _itemId) external { _stakeOneTool(_itemId); } /** * @dev UnStake one inventory item * @param _itemId - NFT tokenId */ function unstakeOneTool(uint8 _itemId) external { _unstakeOneTool(_itemId); } ///////////////////////////////////////////////////// //// Admin functions /////// ///////////////////////////////////////////////////// function setOneCommonAmulet(uint8 _index, address _token) external onlyOwner { COMMON_AMULETS[_index] = _token; } function setAmuletForOneCreature(uint8 _index, address[] memory _tokens) external onlyOwner { delete amulets[_index]; amulets[_index] = _tokens; } function setPriceProvider(address _priceProvider) external onlyOwner { priceProvider = _priceProvider; } function enableReveal(bool _isEnabled) external onlyOwner { REVEAL_ENABLED = _isEnabled; } function enableFarming(bool _isEnabled) external onlyOwner { FARMING_ENABLED = _isEnabled; } //////////////////////////////////////// /// Proxy for NFT Operators mamnage // //////////////////////////////////////// function addOperator(address _contract, address newOperator) external onlyOwner { IOperatorManage(_contract).addOperator(newOperator); } function removeOperator(address _contract, address oldOperator) external onlyOwner { IOperatorManage(_contract).removeOperator(oldOperator); } function reclaimToken(address _contract, IERC20 anyTokens, address _admin) external onlyOwner { IOperatorManage(_contract).withdrawERC20(anyTokens, _admin); } //////////////////////////////////////////////////////// function getCreatureAmulets(uint8 _creatureType) external view returns (address[] memory) { return _getCreatureAmulets(_creatureType); } function _getCreatureAmulets(uint8 _creatureType) internal view returns (address[] memory) { return amulets[_creatureType]; } function getCreatureStat(uint8 _creatureType) external view returns ( uint16, uint16, uint16, uint16, uint16, uint16, uint16, uint16 ) { CreaturesCount storage stat = creaturesBorn[_creatureType]; return ( stat.totalNormie, stat.leftNormie, stat.totalChad, stat.leftChadToDiscover, stat.totalDegen, stat.leftDegenToDiscover, stat.leftChadFarmAttempts, stat.leftDegenFarmAttempts ); } function getWeightedChoice(uint8[] memory _weights) external view returns (uint8){ return _getWeightedChoice(_weights); } function _getWeightedChoice(uint8[] memory _weights) internal view returns (uint8){ uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); return _getWeightedChoice2(_weights, randomSeed); } function getFarmingById(uint256 _farmingId) external view returns (FarmRecord memory) { return farming[_farmingId]; } function getCommonAmuletPrices(uint256 _timestamp) external view returns (uint256[3] memory) { return _getCommonAmuletPrices(_timestamp); } function getOneAmuletPrice(address _token) external view returns (uint256) { return _getOneAmuletPrice(_token); } /////////////////////////////////////////////// /// Internals /////// /////////////////////////////////////////////// /** * @dev Save farming results in storage and mint * appropriate token (NFT, ERC20 or None) */ function _endFarming(uint256 _deployId, Result _res) internal { //TODO need refactor if EGGs will be FarmRecord storage f = farming[_deployId]; f.harvest = _res; // unstake creature ICreatures(farm.creatures).transferFrom(address(this), msg.sender, f.creatureId); eggs.burn(_deployId); // Burn EGG if (_res == Result.Fail) { //unstake land (if staked) if (ILand(farm.land).ownerOf(f.landId) == address(this)){ ILand(farm.land).transferFrom(address(this), msg.sender, f.landId); } emit Harvest( _deployId, msg.sender, uint8(_res), 0, //baseChance 0, //bonus.amuletHold, 0, //bonus.amuletBullTrend, 0 //bonus.inventoryHold ); } } function _stakeOneTool(uint8 _itemId) internal { require(IInventory(farm.inventory).balanceOf(msg.sender, _itemId) >= 1, "You must own this tool for stake!" ); //Before stake we need two checks. //1. Removed //2. Cant`t stake one tool more than one item require(userStakedTools[msg.sender][_itemId] == 0, "Tool is already staked"); //stake IInventory(farm.inventory).safeTransferFrom( msg.sender, address(this), _itemId, 1, bytes('0') ); userStakedTools[msg.sender][_itemId] = block.timestamp; } function _unstakeOneTool(uint8 _itemId) internal { require(userStakedTools[msg.sender][_itemId] > 0, "This tool is not staked yet"); require(block.timestamp - userStakedTools[msg.sender][_itemId] >= getToolUnstakeDelay(), "Cant unstake earlier than a week" ); userStakedTools[msg.sender][_itemId] = 0; IInventory(farm.inventory).safeTransferFrom( address(this), msg.sender, _itemId, 1, bytes('0') ); } function _saveCommonAmuletPrices(uint256 _timestamp) internal { //Lets check if price NOT exist for this timestamp - lets save it if (commonAmuletPrices[_timestamp][0] == 0) { for (uint8 i=0; i < COMMON_AMULETS.length; i++){ commonAmuletPrices[_timestamp][i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } } } function _checkAndSaveMaxAmuletPrice(address _amulet) internal { if (IERC20(_amulet).balanceOf(msg.sender) > maxAmuletBalances[_amulet] ) { maxAmuletBalances[_amulet] = IERC20(_amulet).balanceOf(msg.sender); } } function _getCommonAmuletPrices(uint256 _timestamp) internal view returns (uint256[3] memory) { //Lets check if price allready exist for this timestamp - just return it if (commonAmuletPrices[_timestamp][0] != 0) { return commonAmuletPrices[_timestamp]; } //If price is not exist lets get it from oracles uint256[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ res[i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } return res; } function _getCommonAmuletsHoldState(address _farmer) internal view returns (bool[3] memory) { //If token balance =0 - set false bool[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ if (IERC20(COMMON_AMULETS[i]).balanceOf(_farmer) > 0){ res[i] = true; } else { // Set to zero if token balance is 0 res[i] = false; } } return res; } function _getExistingAmuletsPrices(address[] memory _tokens) internal view returns (uint256[] memory) { uint256[] memory res = new uint256[](_tokens.length); for (uint8 i=0; i < _tokens.length; i++){ if (IERC20(_tokens[i]).balanceOf(msg.sender) > 0){ res[i] = _getOneAmuletPrice(_tokens[i]); } else { // Set to zero if token balance is 0 res[i] = 0; } } return res; } function _getOneAmuletPrice(address _token) internal view returns (uint256) { return IAmuletPriceProvider(priceProvider).getLastPrice(_token); } function _isRevelEnabled() internal view returns (bool) { return REVEAL_ENABLED; } function _reveal(uint randomSeed) internal { require ((landCount.left + allNormiesesLeft) > 0, "Sorry, no more reveal!"); //1. Lets choose Land OR Creature, % //So we have two possible results. 1 - Land, 0 - Creature. // sum of weights = 100, lets define weigth for Creature uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = uint8( uint32(allNormiesesLeft) * CREATURE_P_MULT // * 100 removed due CREATURE_P_MULT / (CREATURE_P_MULT * uint32(allNormiesesLeft) / 100 + uint32(landCount.left)) ); choiceWeight[1] = 100 - choiceWeight[0]; uint8 choice = uint8(_getWeightedChoice2(choiceWeight, randomSeed)); //Check that choice can be executed if (choice != 0 && landCount.left == 0) { //There are no more Lands. So we need change choice choice = 0; } if (choice == 0) { // create creature uint8[] memory choiceWeight0 = new uint8[](getCreatureTypeCount()); //2. Ok, Creature will be born. But what kind of? for (uint8 i = 0; i < getCreatureTypeCount(); i ++) { choiceWeight0[i] = uint8(creaturesBorn[i].leftNormie); } choice = uint8(_getWeightedChoice2(choiceWeight0, randomSeed / 0x10000)); // shift right 16 bits ICreatures(farm.creatures).mint( msg.sender, MAX_ALL_NORMIES - allNormiesesLeft, choice, //AnimalType 0, creaturesBorn[choice].totalNormie - creaturesBorn[choice].leftNormie + 1 // index ); emit Reveal(MAX_ALL_NORMIES - allNormiesesLeft, true, choice); allNormiesesLeft -= 1; creaturesBorn[choice].leftNormie -= 1; } else { // create land ILand(farm.land).mint( msg.sender, getMaxLands() - landCount.left ); emit Reveal(getMaxLands() - landCount.left , false, 0); landCount.left -= 1; } } function _getWeightedChoice2(uint8[] memory _weights, uint randomSeed) internal view returns (uint8){ uint256 sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { sum_of_weights += _weights[i]; } uint256 rnd = randomSeed % sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { if (rnd < _weights[i]) { return i; } rnd -= _weights[i]; } return 0; } /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); } /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)")); } function getCreatureTypeCount() virtual internal view returns (uint16); function getFarmingDuration() virtual internal view returns (uint); function getToolUnstakeDelay() virtual internal view returns (uint); function getNormieCountInType() virtual internal view returns (uint16); function getChadCountInType() virtual internal view returns (uint16); function getMaxLands() virtual internal view returns (uint16); function getUsersTokens(address _owner) external view returns (uint256[] memory) { return eggs.getUsersTokens(_owner); } }
_endFarming
function _endFarming(uint256 _deployId, Result _res) internal { //TODO need refactor if EGGs will be FarmRecord storage f = farming[_deployId]; f.harvest = _res; // unstake creature ICreatures(farm.creatures).transferFrom(address(this), msg.sender, f.creatureId); eggs.burn(_deployId); // Burn EGG if (_res == Result.Fail) { //unstake land (if staked) if (ILand(farm.land).ownerOf(f.landId) == address(this)){ ILand(farm.land).transferFrom(address(this), msg.sender, f.landId); } emit Harvest( _deployId, msg.sender, uint8(_res), 0, //baseChance 0, //bonus.amuletHold, 0, //bonus.amuletBullTrend, 0 //bonus.inventoryHold ); } }
/** * @dev Save farming results in storage and mint * appropriate token (NFT, ERC20 or None) */
NatSpecMultiLine
v0.7.4+commit.3f05b770
MIT
ipfs://308c7d0f38216f626771d86f2b5b3091893bd5f12659a801a1f13db0060ec78f
{ "func_code_index": [ 19844, 20765 ] }
3,318
Creatures
DegensFarmBase.sol
0xd227df494367a8b769b4bf2bbebd0388a8758741
Solidity
DegenFarmBase
abstract contract DegenFarmBase is ERC1155Receiver, Ownable { enum AnimalType { Cow, Horse, Rabbit, Chicken, Pig, Cat, Dog, Goose, Goat, Sheep, Snake, Fish, Frog, Worm, Lama, Mouse, Camel, Donkey, Bee, Duck, GenesisEgg // 20 } enum Rarity { Normie, // 0 Chad, // 1 Degen, // 2 Unique // 3 } enum Result {Fail, Dung, Chad, Degen} //External conatrct addresses used with this farm. struct AddressRegistry { address land; address creatures; address inventory; address bagstoken; address dungtoken; } //Degens Farm Key numbers struct CreaturesCount { uint16 totalNormie; uint16 leftNormie; uint16 totalChad; uint16 leftChadToDiscover; uint16 totalDegen; uint16 leftDegenToDiscover; uint16 leftChadFarmAttempts; uint16 leftDegenFarmAttempts; } //Land count record struct LandCount { uint16 total; uint16 left; } // Record represent one farming act struct FarmRecord { uint256 creatureId; uint256 landId; uint256 harvestTime; uint256[] amuletsPrice1; uint256[] amuletsPrice2; Result harvest; uint256 harvestId; //new NFT tokenId bool[3] commonAmuletInitialHold; } // Bonus for better harvest struct Bonus { uint16 amuletHold; uint16 amuletBullTrend; uint16 inventoryHold; } uint8 constant public CREATURE_TYPE_COUNT_MAX = 20; //how much creatures types may be used //Creature probubility multiplier, scaled with 100. 3.00 - 300, 3.05 - 305 etc // so we need additional divide on 100 in formula uint32 constant public CREATURE_P_MULT = 230; uint16 public MAX_ALL_NORMIES = getCreatureTypeCount() * getNormieCountInType(); //subj uint256 constant public NFT_ID_MULTIPLIER = 10000; //must be set more then all Normies count uint256 constant public FARM_DUNG_AMOUNT = 250e32; //per one harvest uint16 constant public BONUS_POINTS_AMULET_HOLD = 10; uint16 constant public BONUS_POINTS_AMULET_BULL_TREND = 90; //Common Amulet addresses address[3] public COMMON_AMULETS = [ 0xa0246c9032bC3A600820415aE600c6388619A14D, 0x87d73E916D7057945c9BcD8cdd94e42A6F47f776, 0x126c121f99e1E211dF2e5f8De2d96Fa36647c855 ]; bool public REVEAL_ENABLED = false; bool public FARMING_ENABLED = false; address public priceProvider; IEggs public eggs; address[][CREATURE_TYPE_COUNT_MAX] public amulets; //amulets for creatures AddressRegistry public farm; LandCount public landCount; //common token price snapshots mapping(uint256 => uint256[3]) public commonAmuletPrices; mapping(address => uint256) public maxAmuletBalances; // mapping from user to his(her) staked tools // Index of uint256[6] represent tool NFT itemID mapping(address => uint256[6]) public userStakedTools; uint16 public allNormiesesLeft; CreaturesCount[CREATURE_TYPE_COUNT_MAX] public creaturesBorn; FarmRecord[] farming; event Reveal(uint256 indexed _tokenId, bool _isCreature, uint8 _animalType); event Harvest( uint256 indexed _eggId, address farmer, uint8 result , uint16 baseChance, uint16 amuletHold, uint16 amuletBullTrend, uint16 inventoryHold ); constructor ( address _land, address _creatures, address _inventory, address _bagstoken, address _dungtoken, IEggs _eggs ) { farm.land = _land; farm.creatures = _creatures; farm.inventory = _inventory; farm.bagstoken = _bagstoken; farm.dungtoken = _dungtoken; // Index of creaturesBorn in this initial setting // must NOT exceed CREATURE_TYPE_COUNT for (uint i = 0; i < getCreatureTypeCount(); i++) { creaturesBorn[i] = CreaturesCount( getNormieCountInType(), // totalNormie; getNormieCountInType(), // leftNormie; getChadCountInType(), // totalChad; getChadCountInType(), // leftChadToDiscover; 1, // totalDegen; 1, // leftDegenToDiscover; getNormieCountInType(), // leftChadFarmAttempts; getChadCountInType()); // leftDegenFarmAttempts; } landCount = LandCount(getMaxLands(), getMaxLands()); allNormiesesLeft = MAX_ALL_NORMIES; eggs = _eggs; } /** * @dev Changes inventory contract */ function setInventory(address _inventory) external onlyOwner { farm.inventory = _inventory; } function reveal(uint count) external { require(_isRevelEnabled(), "Please wait for reveal enabled."); require(count > 0, "Count must be positive"); require(count <= 8, "Count must less than 9"); // random limit require( IERC20(farm.bagstoken).allowance(msg.sender, address(this)) >= count*1, "Please approve your BAGS token to this contract." ); require( IERC20(farm.bagstoken).transferFrom(msg.sender, address(this), count*1) ); uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); // random seed for 8 reveals (8x32=256) for (uint i = 0; i < count; i++) { _reveal(randomSeed); randomSeed = randomSeed / 0x100000000; // shift right 32 bits } } event Log(string mess); /** * @dev Start farming process. New NFT - Egg will minted for user * @param _creatureId - NFT tokenId, caller must be owner of this token * @param _landId -- NFT tokenId, caller must be owner of this token */ function farmDeploy(uint256 _creatureId, uint256 _landId) external { require(FARMING_ENABLED == true, "Chief Farmer not enable yet"); require(ICreatures(farm.creatures).ownerOf(_creatureId) == msg.sender, "Need to be Creature Owner" ); require(ILand(farm.land).ownerOf(_landId) == msg.sender, "Need to be Land Owner" ); (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity(_creatureId); require((DegenFarmBase.Rarity)(crRarity) == Rarity.Normie || (DegenFarmBase.Rarity)(crRarity) == Rarity.Chad, "Can farm only Normie and Chad"); //Check that farming available yet if (crRarity == 0) { require(creaturesBorn[crType].leftChadToDiscover > 0, "No more chads left"); } else { require(creaturesBorn[crType].leftDegenToDiscover > 0, "No more Degen left"); } //1. Lets make amulet price snapshot //1.1. First we need creat array with properly elements count uint256[] memory prices1 = new uint256[](amulets[crType].length); uint256[] memory prices2 = new uint256[](amulets[crType].length); prices1 = _getExistingAmuletsPrices(amulets[crType]); //2.Check and save Common Amulets price(if not exist yet) _saveCommonAmuletPrices(block.timestamp); //3. Save deploy record farming.push( FarmRecord({ creatureId: _creatureId, landId: _landId, harvestTime: block.timestamp + getFarmingDuration(), amuletsPrice1: prices1, amuletsPrice2: prices2, harvest: Result.Fail, harvestId: 0, commonAmuletInitialHold: _getCommonAmuletsHoldState(msg.sender) //save initial hold state }) ); // Let's mint Egg. eggs.mint( msg.sender, // farmer farming.length - 1 // tokenId ); //STAKE LAND and Creatures!!!! ILand(farm.land).transferFrom(msg.sender, address(this), _landId); ICreatures(farm.creatures).transferFrom(msg.sender, address(this), _creatureId); } /** * @dev Finish farming process. Egg NFT will be burn * @param _deployId - NFT tokenId, caller must be owner of this token */ function harvest(uint256 _deployId) external { require(eggs.ownerOf(_deployId) == msg.sender, "This is NOT YOUR EGG"); FarmRecord storage f = farming[_deployId]; require(f.harvestTime <= block.timestamp, "To early for harvest"); //Lets Calculate Dung/CHAD-DEGEN chance Result farmingResult; Bonus memory bonus; //1. BaseChance (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity( f.creatureId ); uint16 baseChance; if (crRarity == 0) { //Try farm CHAD. So if there is no CHADs any more we must return assets if (creaturesBorn[crType].leftChadToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftChadToDiscover * 100 /(creaturesBorn[crType].leftChadFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftChadFarmAttempts -= 1; } else { //Try farm DEGEN. So if there is no DEGENSs any more we must return assets if (creaturesBorn[crType].leftDegenToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftDegenToDiscover * 100 /(creaturesBorn[crType].leftDegenFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftDegenFarmAttempts -= 1; } ////////////////////////////////////////////// // 2. Bonus for amulet token ***HOLD*** // 3. Bonus for amulets BULLs trend ////////////////////////////////////////////// bonus.amuletHold = 0; bonus.amuletBullTrend = 0; //Check common amulets _saveCommonAmuletPrices(block.timestamp); //Get current hold stae for (uint8 i = 0; i < COMMON_AMULETS.length; i ++){ if (f.commonAmuletInitialHold[i] && _getCommonAmuletsHoldState(msg.sender)[i]) { //token was hold at deploy time and now - iT IS GOOD //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(COMMON_AMULETS[i]); bonus.amuletHold = uint16( IERC20(COMMON_AMULETS[i]).balanceOf(msg.sender) * 100 / maxAmuletBalances[COMMON_AMULETS[i]] * BONUS_POINTS_AMULET_HOLD / 100 //100 used for scale ); //Lets check Bull TREND if (_getCommonAmuletPrices(f.harvestTime - getFarmingDuration())[i] < _getCommonAmuletPrices(block.timestamp)[i] ) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } //Ok, if there is NO common amulets lets check personal uint256[] memory prices2 = new uint256[](amulets[crType].length); prices2 = _getExistingAmuletsPrices(amulets[crType]); if (bonus.amuletHold != BONUS_POINTS_AMULET_HOLD) { for (uint8 i=0; i < f.amuletsPrice1.length; i ++){ if (f.amuletsPrice1[i] > 0 && prices2[i] > 0){ //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(amulets[i][crType]); bonus.amuletHold = uint16( IERC20(amulets[i][crType]).balanceOf(msg.sender) * 100 //100 used for scale / maxAmuletBalances[amulets[i][crType]] * BONUS_POINTS_AMULET_HOLD /100 ); //Lets check Bull TREND if (f.amuletsPrice1[i] < prices2[i]) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } } ////////////////////////////////////////////// ////////////////////////////////////////////// //4. Bonus for inventory ////////////////////////////////////////////// bonus.inventoryHold = 0; if (userStakedTools[msg.sender].length > 0) { for (uint8 i=0; i<userStakedTools[msg.sender].length; i++) { if (userStakedTools[msg.sender][i] > 0){ bonus.inventoryHold = bonus.inventoryHold + IInventory(farm.inventory).getToolBoost(i); } } } ////////////////////////////////////////////// uint16 allBonus = bonus.amuletHold + bonus.amuletBullTrend + bonus.inventoryHold; uint8 chanceOfRarityUP = uint8( (baseChance + allBonus) * 100 / (100 + allBonus) ); uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = chanceOfRarityUP; choiceWeight[1] = 100 - chanceOfRarityUP; uint8 choice = uint8(_getWeightedChoice(choiceWeight)); if (choice == 0) { f.harvestId = (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId; // Mint new chad/degen uint32 index; //Decrease appropriate CREATRURE COUNT if (crRarity + 1 == uint8(Rarity.Chad)) { index = creaturesBorn[crType].totalChad - creaturesBorn[crType].leftChadToDiscover + 1; creaturesBorn[crType].leftChadToDiscover -= 1; farmingResult = Result.Chad; } else if (crRarity + 1 == uint8(Rarity.Degen)) { index = creaturesBorn[crType].totalDegen - creaturesBorn[crType].leftDegenToDiscover + 1; creaturesBorn[crType].leftDegenToDiscover -= 1; farmingResult = Result.Degen; } ICreatures(farm.creatures).mint( msg.sender, (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId, // new iD crType, //AnimalType crRarity + 1, index // index ); } else { //Mint new dung IDung(farm.dungtoken).mint(msg.sender, FARM_DUNG_AMOUNT); farmingResult = Result.Dung; } //BURN Land ILand(farm.land).burn(f.landId); _endFarming(_deployId, farmingResult); emit Harvest( _deployId, msg.sender, uint8(farmingResult), baseChance, bonus.amuletHold, bonus.amuletBullTrend, bonus.inventoryHold ); } /** * @dev Stake one inventory item * @param _itemId - NFT tokenId, caller must be owner of this token */ function stakeOneTool(uint8 _itemId) external { _stakeOneTool(_itemId); } /** * @dev UnStake one inventory item * @param _itemId - NFT tokenId */ function unstakeOneTool(uint8 _itemId) external { _unstakeOneTool(_itemId); } ///////////////////////////////////////////////////// //// Admin functions /////// ///////////////////////////////////////////////////// function setOneCommonAmulet(uint8 _index, address _token) external onlyOwner { COMMON_AMULETS[_index] = _token; } function setAmuletForOneCreature(uint8 _index, address[] memory _tokens) external onlyOwner { delete amulets[_index]; amulets[_index] = _tokens; } function setPriceProvider(address _priceProvider) external onlyOwner { priceProvider = _priceProvider; } function enableReveal(bool _isEnabled) external onlyOwner { REVEAL_ENABLED = _isEnabled; } function enableFarming(bool _isEnabled) external onlyOwner { FARMING_ENABLED = _isEnabled; } //////////////////////////////////////// /// Proxy for NFT Operators mamnage // //////////////////////////////////////// function addOperator(address _contract, address newOperator) external onlyOwner { IOperatorManage(_contract).addOperator(newOperator); } function removeOperator(address _contract, address oldOperator) external onlyOwner { IOperatorManage(_contract).removeOperator(oldOperator); } function reclaimToken(address _contract, IERC20 anyTokens, address _admin) external onlyOwner { IOperatorManage(_contract).withdrawERC20(anyTokens, _admin); } //////////////////////////////////////////////////////// function getCreatureAmulets(uint8 _creatureType) external view returns (address[] memory) { return _getCreatureAmulets(_creatureType); } function _getCreatureAmulets(uint8 _creatureType) internal view returns (address[] memory) { return amulets[_creatureType]; } function getCreatureStat(uint8 _creatureType) external view returns ( uint16, uint16, uint16, uint16, uint16, uint16, uint16, uint16 ) { CreaturesCount storage stat = creaturesBorn[_creatureType]; return ( stat.totalNormie, stat.leftNormie, stat.totalChad, stat.leftChadToDiscover, stat.totalDegen, stat.leftDegenToDiscover, stat.leftChadFarmAttempts, stat.leftDegenFarmAttempts ); } function getWeightedChoice(uint8[] memory _weights) external view returns (uint8){ return _getWeightedChoice(_weights); } function _getWeightedChoice(uint8[] memory _weights) internal view returns (uint8){ uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); return _getWeightedChoice2(_weights, randomSeed); } function getFarmingById(uint256 _farmingId) external view returns (FarmRecord memory) { return farming[_farmingId]; } function getCommonAmuletPrices(uint256 _timestamp) external view returns (uint256[3] memory) { return _getCommonAmuletPrices(_timestamp); } function getOneAmuletPrice(address _token) external view returns (uint256) { return _getOneAmuletPrice(_token); } /////////////////////////////////////////////// /// Internals /////// /////////////////////////////////////////////// /** * @dev Save farming results in storage and mint * appropriate token (NFT, ERC20 or None) */ function _endFarming(uint256 _deployId, Result _res) internal { //TODO need refactor if EGGs will be FarmRecord storage f = farming[_deployId]; f.harvest = _res; // unstake creature ICreatures(farm.creatures).transferFrom(address(this), msg.sender, f.creatureId); eggs.burn(_deployId); // Burn EGG if (_res == Result.Fail) { //unstake land (if staked) if (ILand(farm.land).ownerOf(f.landId) == address(this)){ ILand(farm.land).transferFrom(address(this), msg.sender, f.landId); } emit Harvest( _deployId, msg.sender, uint8(_res), 0, //baseChance 0, //bonus.amuletHold, 0, //bonus.amuletBullTrend, 0 //bonus.inventoryHold ); } } function _stakeOneTool(uint8 _itemId) internal { require(IInventory(farm.inventory).balanceOf(msg.sender, _itemId) >= 1, "You must own this tool for stake!" ); //Before stake we need two checks. //1. Removed //2. Cant`t stake one tool more than one item require(userStakedTools[msg.sender][_itemId] == 0, "Tool is already staked"); //stake IInventory(farm.inventory).safeTransferFrom( msg.sender, address(this), _itemId, 1, bytes('0') ); userStakedTools[msg.sender][_itemId] = block.timestamp; } function _unstakeOneTool(uint8 _itemId) internal { require(userStakedTools[msg.sender][_itemId] > 0, "This tool is not staked yet"); require(block.timestamp - userStakedTools[msg.sender][_itemId] >= getToolUnstakeDelay(), "Cant unstake earlier than a week" ); userStakedTools[msg.sender][_itemId] = 0; IInventory(farm.inventory).safeTransferFrom( address(this), msg.sender, _itemId, 1, bytes('0') ); } function _saveCommonAmuletPrices(uint256 _timestamp) internal { //Lets check if price NOT exist for this timestamp - lets save it if (commonAmuletPrices[_timestamp][0] == 0) { for (uint8 i=0; i < COMMON_AMULETS.length; i++){ commonAmuletPrices[_timestamp][i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } } } function _checkAndSaveMaxAmuletPrice(address _amulet) internal { if (IERC20(_amulet).balanceOf(msg.sender) > maxAmuletBalances[_amulet] ) { maxAmuletBalances[_amulet] = IERC20(_amulet).balanceOf(msg.sender); } } function _getCommonAmuletPrices(uint256 _timestamp) internal view returns (uint256[3] memory) { //Lets check if price allready exist for this timestamp - just return it if (commonAmuletPrices[_timestamp][0] != 0) { return commonAmuletPrices[_timestamp]; } //If price is not exist lets get it from oracles uint256[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ res[i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } return res; } function _getCommonAmuletsHoldState(address _farmer) internal view returns (bool[3] memory) { //If token balance =0 - set false bool[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ if (IERC20(COMMON_AMULETS[i]).balanceOf(_farmer) > 0){ res[i] = true; } else { // Set to zero if token balance is 0 res[i] = false; } } return res; } function _getExistingAmuletsPrices(address[] memory _tokens) internal view returns (uint256[] memory) { uint256[] memory res = new uint256[](_tokens.length); for (uint8 i=0; i < _tokens.length; i++){ if (IERC20(_tokens[i]).balanceOf(msg.sender) > 0){ res[i] = _getOneAmuletPrice(_tokens[i]); } else { // Set to zero if token balance is 0 res[i] = 0; } } return res; } function _getOneAmuletPrice(address _token) internal view returns (uint256) { return IAmuletPriceProvider(priceProvider).getLastPrice(_token); } function _isRevelEnabled() internal view returns (bool) { return REVEAL_ENABLED; } function _reveal(uint randomSeed) internal { require ((landCount.left + allNormiesesLeft) > 0, "Sorry, no more reveal!"); //1. Lets choose Land OR Creature, % //So we have two possible results. 1 - Land, 0 - Creature. // sum of weights = 100, lets define weigth for Creature uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = uint8( uint32(allNormiesesLeft) * CREATURE_P_MULT // * 100 removed due CREATURE_P_MULT / (CREATURE_P_MULT * uint32(allNormiesesLeft) / 100 + uint32(landCount.left)) ); choiceWeight[1] = 100 - choiceWeight[0]; uint8 choice = uint8(_getWeightedChoice2(choiceWeight, randomSeed)); //Check that choice can be executed if (choice != 0 && landCount.left == 0) { //There are no more Lands. So we need change choice choice = 0; } if (choice == 0) { // create creature uint8[] memory choiceWeight0 = new uint8[](getCreatureTypeCount()); //2. Ok, Creature will be born. But what kind of? for (uint8 i = 0; i < getCreatureTypeCount(); i ++) { choiceWeight0[i] = uint8(creaturesBorn[i].leftNormie); } choice = uint8(_getWeightedChoice2(choiceWeight0, randomSeed / 0x10000)); // shift right 16 bits ICreatures(farm.creatures).mint( msg.sender, MAX_ALL_NORMIES - allNormiesesLeft, choice, //AnimalType 0, creaturesBorn[choice].totalNormie - creaturesBorn[choice].leftNormie + 1 // index ); emit Reveal(MAX_ALL_NORMIES - allNormiesesLeft, true, choice); allNormiesesLeft -= 1; creaturesBorn[choice].leftNormie -= 1; } else { // create land ILand(farm.land).mint( msg.sender, getMaxLands() - landCount.left ); emit Reveal(getMaxLands() - landCount.left , false, 0); landCount.left -= 1; } } function _getWeightedChoice2(uint8[] memory _weights, uint randomSeed) internal view returns (uint8){ uint256 sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { sum_of_weights += _weights[i]; } uint256 rnd = randomSeed % sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { if (rnd < _weights[i]) { return i; } rnd -= _weights[i]; } return 0; } /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); } /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)")); } function getCreatureTypeCount() virtual internal view returns (uint16); function getFarmingDuration() virtual internal view returns (uint); function getToolUnstakeDelay() virtual internal view returns (uint); function getNormieCountInType() virtual internal view returns (uint16); function getChadCountInType() virtual internal view returns (uint16); function getMaxLands() virtual internal view returns (uint16); function getUsersTokens(address _owner) external view returns (uint256[] memory) { return eggs.getUsersTokens(_owner); } }
onERC1155Received
function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); }
/** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */
NatSpecMultiLine
v0.7.4+commit.3f05b770
MIT
ipfs://308c7d0f38216f626771d86f2b5b3091893bd5f12659a801a1f13db0060ec78f
{ "func_code_index": [ 28088, 28427 ] }
3,319
Creatures
DegensFarmBase.sol
0xd227df494367a8b769b4bf2bbebd0388a8758741
Solidity
DegenFarmBase
abstract contract DegenFarmBase is ERC1155Receiver, Ownable { enum AnimalType { Cow, Horse, Rabbit, Chicken, Pig, Cat, Dog, Goose, Goat, Sheep, Snake, Fish, Frog, Worm, Lama, Mouse, Camel, Donkey, Bee, Duck, GenesisEgg // 20 } enum Rarity { Normie, // 0 Chad, // 1 Degen, // 2 Unique // 3 } enum Result {Fail, Dung, Chad, Degen} //External conatrct addresses used with this farm. struct AddressRegistry { address land; address creatures; address inventory; address bagstoken; address dungtoken; } //Degens Farm Key numbers struct CreaturesCount { uint16 totalNormie; uint16 leftNormie; uint16 totalChad; uint16 leftChadToDiscover; uint16 totalDegen; uint16 leftDegenToDiscover; uint16 leftChadFarmAttempts; uint16 leftDegenFarmAttempts; } //Land count record struct LandCount { uint16 total; uint16 left; } // Record represent one farming act struct FarmRecord { uint256 creatureId; uint256 landId; uint256 harvestTime; uint256[] amuletsPrice1; uint256[] amuletsPrice2; Result harvest; uint256 harvestId; //new NFT tokenId bool[3] commonAmuletInitialHold; } // Bonus for better harvest struct Bonus { uint16 amuletHold; uint16 amuletBullTrend; uint16 inventoryHold; } uint8 constant public CREATURE_TYPE_COUNT_MAX = 20; //how much creatures types may be used //Creature probubility multiplier, scaled with 100. 3.00 - 300, 3.05 - 305 etc // so we need additional divide on 100 in formula uint32 constant public CREATURE_P_MULT = 230; uint16 public MAX_ALL_NORMIES = getCreatureTypeCount() * getNormieCountInType(); //subj uint256 constant public NFT_ID_MULTIPLIER = 10000; //must be set more then all Normies count uint256 constant public FARM_DUNG_AMOUNT = 250e32; //per one harvest uint16 constant public BONUS_POINTS_AMULET_HOLD = 10; uint16 constant public BONUS_POINTS_AMULET_BULL_TREND = 90; //Common Amulet addresses address[3] public COMMON_AMULETS = [ 0xa0246c9032bC3A600820415aE600c6388619A14D, 0x87d73E916D7057945c9BcD8cdd94e42A6F47f776, 0x126c121f99e1E211dF2e5f8De2d96Fa36647c855 ]; bool public REVEAL_ENABLED = false; bool public FARMING_ENABLED = false; address public priceProvider; IEggs public eggs; address[][CREATURE_TYPE_COUNT_MAX] public amulets; //amulets for creatures AddressRegistry public farm; LandCount public landCount; //common token price snapshots mapping(uint256 => uint256[3]) public commonAmuletPrices; mapping(address => uint256) public maxAmuletBalances; // mapping from user to his(her) staked tools // Index of uint256[6] represent tool NFT itemID mapping(address => uint256[6]) public userStakedTools; uint16 public allNormiesesLeft; CreaturesCount[CREATURE_TYPE_COUNT_MAX] public creaturesBorn; FarmRecord[] farming; event Reveal(uint256 indexed _tokenId, bool _isCreature, uint8 _animalType); event Harvest( uint256 indexed _eggId, address farmer, uint8 result , uint16 baseChance, uint16 amuletHold, uint16 amuletBullTrend, uint16 inventoryHold ); constructor ( address _land, address _creatures, address _inventory, address _bagstoken, address _dungtoken, IEggs _eggs ) { farm.land = _land; farm.creatures = _creatures; farm.inventory = _inventory; farm.bagstoken = _bagstoken; farm.dungtoken = _dungtoken; // Index of creaturesBorn in this initial setting // must NOT exceed CREATURE_TYPE_COUNT for (uint i = 0; i < getCreatureTypeCount(); i++) { creaturesBorn[i] = CreaturesCount( getNormieCountInType(), // totalNormie; getNormieCountInType(), // leftNormie; getChadCountInType(), // totalChad; getChadCountInType(), // leftChadToDiscover; 1, // totalDegen; 1, // leftDegenToDiscover; getNormieCountInType(), // leftChadFarmAttempts; getChadCountInType()); // leftDegenFarmAttempts; } landCount = LandCount(getMaxLands(), getMaxLands()); allNormiesesLeft = MAX_ALL_NORMIES; eggs = _eggs; } /** * @dev Changes inventory contract */ function setInventory(address _inventory) external onlyOwner { farm.inventory = _inventory; } function reveal(uint count) external { require(_isRevelEnabled(), "Please wait for reveal enabled."); require(count > 0, "Count must be positive"); require(count <= 8, "Count must less than 9"); // random limit require( IERC20(farm.bagstoken).allowance(msg.sender, address(this)) >= count*1, "Please approve your BAGS token to this contract." ); require( IERC20(farm.bagstoken).transferFrom(msg.sender, address(this), count*1) ); uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); // random seed for 8 reveals (8x32=256) for (uint i = 0; i < count; i++) { _reveal(randomSeed); randomSeed = randomSeed / 0x100000000; // shift right 32 bits } } event Log(string mess); /** * @dev Start farming process. New NFT - Egg will minted for user * @param _creatureId - NFT tokenId, caller must be owner of this token * @param _landId -- NFT tokenId, caller must be owner of this token */ function farmDeploy(uint256 _creatureId, uint256 _landId) external { require(FARMING_ENABLED == true, "Chief Farmer not enable yet"); require(ICreatures(farm.creatures).ownerOf(_creatureId) == msg.sender, "Need to be Creature Owner" ); require(ILand(farm.land).ownerOf(_landId) == msg.sender, "Need to be Land Owner" ); (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity(_creatureId); require((DegenFarmBase.Rarity)(crRarity) == Rarity.Normie || (DegenFarmBase.Rarity)(crRarity) == Rarity.Chad, "Can farm only Normie and Chad"); //Check that farming available yet if (crRarity == 0) { require(creaturesBorn[crType].leftChadToDiscover > 0, "No more chads left"); } else { require(creaturesBorn[crType].leftDegenToDiscover > 0, "No more Degen left"); } //1. Lets make amulet price snapshot //1.1. First we need creat array with properly elements count uint256[] memory prices1 = new uint256[](amulets[crType].length); uint256[] memory prices2 = new uint256[](amulets[crType].length); prices1 = _getExistingAmuletsPrices(amulets[crType]); //2.Check and save Common Amulets price(if not exist yet) _saveCommonAmuletPrices(block.timestamp); //3. Save deploy record farming.push( FarmRecord({ creatureId: _creatureId, landId: _landId, harvestTime: block.timestamp + getFarmingDuration(), amuletsPrice1: prices1, amuletsPrice2: prices2, harvest: Result.Fail, harvestId: 0, commonAmuletInitialHold: _getCommonAmuletsHoldState(msg.sender) //save initial hold state }) ); // Let's mint Egg. eggs.mint( msg.sender, // farmer farming.length - 1 // tokenId ); //STAKE LAND and Creatures!!!! ILand(farm.land).transferFrom(msg.sender, address(this), _landId); ICreatures(farm.creatures).transferFrom(msg.sender, address(this), _creatureId); } /** * @dev Finish farming process. Egg NFT will be burn * @param _deployId - NFT tokenId, caller must be owner of this token */ function harvest(uint256 _deployId) external { require(eggs.ownerOf(_deployId) == msg.sender, "This is NOT YOUR EGG"); FarmRecord storage f = farming[_deployId]; require(f.harvestTime <= block.timestamp, "To early for harvest"); //Lets Calculate Dung/CHAD-DEGEN chance Result farmingResult; Bonus memory bonus; //1. BaseChance (uint8 crType, uint8 crRarity) = ICreatures(farm.creatures).getTypeAndRarity( f.creatureId ); uint16 baseChance; if (crRarity == 0) { //Try farm CHAD. So if there is no CHADs any more we must return assets if (creaturesBorn[crType].leftChadToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftChadToDiscover * 100 /(creaturesBorn[crType].leftChadFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftChadFarmAttempts -= 1; } else { //Try farm DEGEN. So if there is no DEGENSs any more we must return assets if (creaturesBorn[crType].leftDegenToDiscover == 0) { _endFarming(_deployId, Result.Fail); return; } baseChance = creaturesBorn[crType].leftDegenToDiscover * 100 /(creaturesBorn[crType].leftDegenFarmAttempts); //Decrease appropriate farm ATTEMPTS COUNT!!! creaturesBorn[crType].leftDegenFarmAttempts -= 1; } ////////////////////////////////////////////// // 2. Bonus for amulet token ***HOLD*** // 3. Bonus for amulets BULLs trend ////////////////////////////////////////////// bonus.amuletHold = 0; bonus.amuletBullTrend = 0; //Check common amulets _saveCommonAmuletPrices(block.timestamp); //Get current hold stae for (uint8 i = 0; i < COMMON_AMULETS.length; i ++){ if (f.commonAmuletInitialHold[i] && _getCommonAmuletsHoldState(msg.sender)[i]) { //token was hold at deploy time and now - iT IS GOOD //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(COMMON_AMULETS[i]); bonus.amuletHold = uint16( IERC20(COMMON_AMULETS[i]).balanceOf(msg.sender) * 100 / maxAmuletBalances[COMMON_AMULETS[i]] * BONUS_POINTS_AMULET_HOLD / 100 //100 used for scale ); //Lets check Bull TREND if (_getCommonAmuletPrices(f.harvestTime - getFarmingDuration())[i] < _getCommonAmuletPrices(block.timestamp)[i] ) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } //Ok, if there is NO common amulets lets check personal uint256[] memory prices2 = new uint256[](amulets[crType].length); prices2 = _getExistingAmuletsPrices(amulets[crType]); if (bonus.amuletHold != BONUS_POINTS_AMULET_HOLD) { for (uint8 i=0; i < f.amuletsPrice1.length; i ++){ if (f.amuletsPrice1[i] > 0 && prices2[i] > 0){ //Lets check max Balance, because //bonus.amuletHold = userAmuletBalance/maxAmuletBalances*BONUS_POINTS_AMULET_HOLD _checkAndSaveMaxAmuletPrice(amulets[i][crType]); bonus.amuletHold = uint16( IERC20(amulets[i][crType]).balanceOf(msg.sender) * 100 //100 used for scale / maxAmuletBalances[amulets[i][crType]] * BONUS_POINTS_AMULET_HOLD /100 ); //Lets check Bull TREND if (f.amuletsPrice1[i] < prices2[i]) { bonus.amuletBullTrend = BONUS_POINTS_AMULET_BULL_TREND; } break; } } } ////////////////////////////////////////////// ////////////////////////////////////////////// //4. Bonus for inventory ////////////////////////////////////////////// bonus.inventoryHold = 0; if (userStakedTools[msg.sender].length > 0) { for (uint8 i=0; i<userStakedTools[msg.sender].length; i++) { if (userStakedTools[msg.sender][i] > 0){ bonus.inventoryHold = bonus.inventoryHold + IInventory(farm.inventory).getToolBoost(i); } } } ////////////////////////////////////////////// uint16 allBonus = bonus.amuletHold + bonus.amuletBullTrend + bonus.inventoryHold; uint8 chanceOfRarityUP = uint8( (baseChance + allBonus) * 100 / (100 + allBonus) ); uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = chanceOfRarityUP; choiceWeight[1] = 100 - chanceOfRarityUP; uint8 choice = uint8(_getWeightedChoice(choiceWeight)); if (choice == 0) { f.harvestId = (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId; // Mint new chad/degen uint32 index; //Decrease appropriate CREATRURE COUNT if (crRarity + 1 == uint8(Rarity.Chad)) { index = creaturesBorn[crType].totalChad - creaturesBorn[crType].leftChadToDiscover + 1; creaturesBorn[crType].leftChadToDiscover -= 1; farmingResult = Result.Chad; } else if (crRarity + 1 == uint8(Rarity.Degen)) { index = creaturesBorn[crType].totalDegen - creaturesBorn[crType].leftDegenToDiscover + 1; creaturesBorn[crType].leftDegenToDiscover -= 1; farmingResult = Result.Degen; } ICreatures(farm.creatures).mint( msg.sender, (crRarity + 1) * NFT_ID_MULTIPLIER + _deployId, // new iD crType, //AnimalType crRarity + 1, index // index ); } else { //Mint new dung IDung(farm.dungtoken).mint(msg.sender, FARM_DUNG_AMOUNT); farmingResult = Result.Dung; } //BURN Land ILand(farm.land).burn(f.landId); _endFarming(_deployId, farmingResult); emit Harvest( _deployId, msg.sender, uint8(farmingResult), baseChance, bonus.amuletHold, bonus.amuletBullTrend, bonus.inventoryHold ); } /** * @dev Stake one inventory item * @param _itemId - NFT tokenId, caller must be owner of this token */ function stakeOneTool(uint8 _itemId) external { _stakeOneTool(_itemId); } /** * @dev UnStake one inventory item * @param _itemId - NFT tokenId */ function unstakeOneTool(uint8 _itemId) external { _unstakeOneTool(_itemId); } ///////////////////////////////////////////////////// //// Admin functions /////// ///////////////////////////////////////////////////// function setOneCommonAmulet(uint8 _index, address _token) external onlyOwner { COMMON_AMULETS[_index] = _token; } function setAmuletForOneCreature(uint8 _index, address[] memory _tokens) external onlyOwner { delete amulets[_index]; amulets[_index] = _tokens; } function setPriceProvider(address _priceProvider) external onlyOwner { priceProvider = _priceProvider; } function enableReveal(bool _isEnabled) external onlyOwner { REVEAL_ENABLED = _isEnabled; } function enableFarming(bool _isEnabled) external onlyOwner { FARMING_ENABLED = _isEnabled; } //////////////////////////////////////// /// Proxy for NFT Operators mamnage // //////////////////////////////////////// function addOperator(address _contract, address newOperator) external onlyOwner { IOperatorManage(_contract).addOperator(newOperator); } function removeOperator(address _contract, address oldOperator) external onlyOwner { IOperatorManage(_contract).removeOperator(oldOperator); } function reclaimToken(address _contract, IERC20 anyTokens, address _admin) external onlyOwner { IOperatorManage(_contract).withdrawERC20(anyTokens, _admin); } //////////////////////////////////////////////////////// function getCreatureAmulets(uint8 _creatureType) external view returns (address[] memory) { return _getCreatureAmulets(_creatureType); } function _getCreatureAmulets(uint8 _creatureType) internal view returns (address[] memory) { return amulets[_creatureType]; } function getCreatureStat(uint8 _creatureType) external view returns ( uint16, uint16, uint16, uint16, uint16, uint16, uint16, uint16 ) { CreaturesCount storage stat = creaturesBorn[_creatureType]; return ( stat.totalNormie, stat.leftNormie, stat.totalChad, stat.leftChadToDiscover, stat.totalDegen, stat.leftDegenToDiscover, stat.leftChadFarmAttempts, stat.leftDegenFarmAttempts ); } function getWeightedChoice(uint8[] memory _weights) external view returns (uint8){ return _getWeightedChoice(_weights); } function _getWeightedChoice(uint8[] memory _weights) internal view returns (uint8){ uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender))); return _getWeightedChoice2(_weights, randomSeed); } function getFarmingById(uint256 _farmingId) external view returns (FarmRecord memory) { return farming[_farmingId]; } function getCommonAmuletPrices(uint256 _timestamp) external view returns (uint256[3] memory) { return _getCommonAmuletPrices(_timestamp); } function getOneAmuletPrice(address _token) external view returns (uint256) { return _getOneAmuletPrice(_token); } /////////////////////////////////////////////// /// Internals /////// /////////////////////////////////////////////// /** * @dev Save farming results in storage and mint * appropriate token (NFT, ERC20 or None) */ function _endFarming(uint256 _deployId, Result _res) internal { //TODO need refactor if EGGs will be FarmRecord storage f = farming[_deployId]; f.harvest = _res; // unstake creature ICreatures(farm.creatures).transferFrom(address(this), msg.sender, f.creatureId); eggs.burn(_deployId); // Burn EGG if (_res == Result.Fail) { //unstake land (if staked) if (ILand(farm.land).ownerOf(f.landId) == address(this)){ ILand(farm.land).transferFrom(address(this), msg.sender, f.landId); } emit Harvest( _deployId, msg.sender, uint8(_res), 0, //baseChance 0, //bonus.amuletHold, 0, //bonus.amuletBullTrend, 0 //bonus.inventoryHold ); } } function _stakeOneTool(uint8 _itemId) internal { require(IInventory(farm.inventory).balanceOf(msg.sender, _itemId) >= 1, "You must own this tool for stake!" ); //Before stake we need two checks. //1. Removed //2. Cant`t stake one tool more than one item require(userStakedTools[msg.sender][_itemId] == 0, "Tool is already staked"); //stake IInventory(farm.inventory).safeTransferFrom( msg.sender, address(this), _itemId, 1, bytes('0') ); userStakedTools[msg.sender][_itemId] = block.timestamp; } function _unstakeOneTool(uint8 _itemId) internal { require(userStakedTools[msg.sender][_itemId] > 0, "This tool is not staked yet"); require(block.timestamp - userStakedTools[msg.sender][_itemId] >= getToolUnstakeDelay(), "Cant unstake earlier than a week" ); userStakedTools[msg.sender][_itemId] = 0; IInventory(farm.inventory).safeTransferFrom( address(this), msg.sender, _itemId, 1, bytes('0') ); } function _saveCommonAmuletPrices(uint256 _timestamp) internal { //Lets check if price NOT exist for this timestamp - lets save it if (commonAmuletPrices[_timestamp][0] == 0) { for (uint8 i=0; i < COMMON_AMULETS.length; i++){ commonAmuletPrices[_timestamp][i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } } } function _checkAndSaveMaxAmuletPrice(address _amulet) internal { if (IERC20(_amulet).balanceOf(msg.sender) > maxAmuletBalances[_amulet] ) { maxAmuletBalances[_amulet] = IERC20(_amulet).balanceOf(msg.sender); } } function _getCommonAmuletPrices(uint256 _timestamp) internal view returns (uint256[3] memory) { //Lets check if price allready exist for this timestamp - just return it if (commonAmuletPrices[_timestamp][0] != 0) { return commonAmuletPrices[_timestamp]; } //If price is not exist lets get it from oracles uint256[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ res[i] = _getOneAmuletPrice(COMMON_AMULETS[i]); } return res; } function _getCommonAmuletsHoldState(address _farmer) internal view returns (bool[3] memory) { //If token balance =0 - set false bool[3] memory res; for (uint8 i=0; i < COMMON_AMULETS.length; i++){ if (IERC20(COMMON_AMULETS[i]).balanceOf(_farmer) > 0){ res[i] = true; } else { // Set to zero if token balance is 0 res[i] = false; } } return res; } function _getExistingAmuletsPrices(address[] memory _tokens) internal view returns (uint256[] memory) { uint256[] memory res = new uint256[](_tokens.length); for (uint8 i=0; i < _tokens.length; i++){ if (IERC20(_tokens[i]).balanceOf(msg.sender) > 0){ res[i] = _getOneAmuletPrice(_tokens[i]); } else { // Set to zero if token balance is 0 res[i] = 0; } } return res; } function _getOneAmuletPrice(address _token) internal view returns (uint256) { return IAmuletPriceProvider(priceProvider).getLastPrice(_token); } function _isRevelEnabled() internal view returns (bool) { return REVEAL_ENABLED; } function _reveal(uint randomSeed) internal { require ((landCount.left + allNormiesesLeft) > 0, "Sorry, no more reveal!"); //1. Lets choose Land OR Creature, % //So we have two possible results. 1 - Land, 0 - Creature. // sum of weights = 100, lets define weigth for Creature uint8[] memory choiceWeight = new uint8[](2); choiceWeight[0] = uint8( uint32(allNormiesesLeft) * CREATURE_P_MULT // * 100 removed due CREATURE_P_MULT / (CREATURE_P_MULT * uint32(allNormiesesLeft) / 100 + uint32(landCount.left)) ); choiceWeight[1] = 100 - choiceWeight[0]; uint8 choice = uint8(_getWeightedChoice2(choiceWeight, randomSeed)); //Check that choice can be executed if (choice != 0 && landCount.left == 0) { //There are no more Lands. So we need change choice choice = 0; } if (choice == 0) { // create creature uint8[] memory choiceWeight0 = new uint8[](getCreatureTypeCount()); //2. Ok, Creature will be born. But what kind of? for (uint8 i = 0; i < getCreatureTypeCount(); i ++) { choiceWeight0[i] = uint8(creaturesBorn[i].leftNormie); } choice = uint8(_getWeightedChoice2(choiceWeight0, randomSeed / 0x10000)); // shift right 16 bits ICreatures(farm.creatures).mint( msg.sender, MAX_ALL_NORMIES - allNormiesesLeft, choice, //AnimalType 0, creaturesBorn[choice].totalNormie - creaturesBorn[choice].leftNormie + 1 // index ); emit Reveal(MAX_ALL_NORMIES - allNormiesesLeft, true, choice); allNormiesesLeft -= 1; creaturesBorn[choice].leftNormie -= 1; } else { // create land ILand(farm.land).mint( msg.sender, getMaxLands() - landCount.left ); emit Reveal(getMaxLands() - landCount.left , false, 0); landCount.left -= 1; } } function _getWeightedChoice2(uint8[] memory _weights, uint randomSeed) internal view returns (uint8){ uint256 sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { sum_of_weights += _weights[i]; } uint256 rnd = randomSeed % sum_of_weights; for (uint8 i = 0; i < _weights.length; i++) { if (rnd < _weights[i]) { return i; } rnd -= _weights[i]; } return 0; } /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); } /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)")); } function getCreatureTypeCount() virtual internal view returns (uint16); function getFarmingDuration() virtual internal view returns (uint); function getToolUnstakeDelay() virtual internal view returns (uint); function getNormieCountInType() virtual internal view returns (uint16); function getChadCountInType() virtual internal view returns (uint16); function getMaxLands() virtual internal view returns (uint16); function getUsersTokens(address _owner) external view returns (uint256[] memory) { return eggs.getUsersTokens(_owner); } }
onERC1155BatchReceived
function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns(bytes4) { return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)")); }
/** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */
NatSpecMultiLine
v0.7.4+commit.3f05b770
MIT
ipfs://308c7d0f38216f626771d86f2b5b3091893bd5f12659a801a1f13db0060ec78f
{ "func_code_index": [ 29425, 29794 ] }
3,320
BondingShareV2
contracts/BondingFormulas.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingFormulas
contract BondingFormulas { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; uint256 public constant ONE = uint256(1 ether); // 18 decimals /// @dev formula UBQ Rights corresponding to a bonding shares LP amount /// @param _bond , bonding share /// @param _amount , amount of LP tokens /// @notice shares = (bond.shares * _amount ) / bond.lpAmount ; function sharesForLP( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256 _uLP) { bytes16 a = _shareInfo[0].fromUInt(); // shares amount bytes16 v = _amount.fromUInt(); bytes16 t = _bond.lpAmount.fromUInt(); _uLP = a.mul(v).div(t).toUInt(); } /// @dev formula may add a decreasing rewards if locking end is near when removing liquidity /// @param _bond , bonding share /// @param _amount , amount of LP tokens /// @notice rewards = _amount; // solhint-disable-block no-unused-vars /* solhint-disable no-unused-vars */ function lpRewardsRemoveLiquidityNormalization( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256) { return _amount; } /* solhint-enable no-unused-vars */ /// @dev formula may add a decreasing rewards if locking end is near when adding liquidity /// @param _bond , bonding share /// @param _amount , amount of LP tokens /// @notice rewards = _amount; // solhint-disable-block no-unused-vars /* solhint-disable no-unused-vars */ function lpRewardsAddLiquidityNormalization( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256) { return _amount; } /* solhint-enable no-unused-vars */ /// @dev formula to calculate the corrected amount to withdraw based on the proportion of /// lp deposited against actual LP token on thge bonding contract /// @param _totalLpDeposited , Total amount of LP deposited by users /// @param _bondingLpBalance , actual bonding contract LP tokens balance minus lp rewards /// @param _amount , amount of LP tokens /// @notice corrected_amount = amount * ( bondingLpBalance / totalLpDeposited) /// if there is more or the same amount of LP than deposited then do nothing function correctedAmountToWithdraw( uint256 _totalLpDeposited, uint256 _bondingLpBalance, uint256 _amount ) public pure returns (uint256) { if (_bondingLpBalance < _totalLpDeposited && _bondingLpBalance > 0) { // if there is less LP token inside the bonding contract that what have been deposited // we have to reduce proportionnaly the lp amount to withdraw return _amount .fromUInt() .mul(_bondingLpBalance.fromUInt()) .div(_totalLpDeposited.fromUInt()) .toUInt(); } return _amount; } }
sharesForLP
function sharesForLP( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256 _uLP) { bytes16 a = _shareInfo[0].fromUInt(); // shares amount bytes16 v = _amount.fromUInt(); bytes16 t = _bond.lpAmount.fromUInt(); _uLP = a.mul(v).div(t).toUInt(); }
/// @dev formula UBQ Rights corresponding to a bonding shares LP amount /// @param _bond , bonding share /// @param _amount , amount of LP tokens /// @notice shares = (bond.shares * _amount ) / bond.lpAmount ;
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 397, 767 ] }
3,321
BondingShareV2
contracts/BondingFormulas.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingFormulas
contract BondingFormulas { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; uint256 public constant ONE = uint256(1 ether); // 18 decimals /// @dev formula UBQ Rights corresponding to a bonding shares LP amount /// @param _bond , bonding share /// @param _amount , amount of LP tokens /// @notice shares = (bond.shares * _amount ) / bond.lpAmount ; function sharesForLP( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256 _uLP) { bytes16 a = _shareInfo[0].fromUInt(); // shares amount bytes16 v = _amount.fromUInt(); bytes16 t = _bond.lpAmount.fromUInt(); _uLP = a.mul(v).div(t).toUInt(); } /// @dev formula may add a decreasing rewards if locking end is near when removing liquidity /// @param _bond , bonding share /// @param _amount , amount of LP tokens /// @notice rewards = _amount; // solhint-disable-block no-unused-vars /* solhint-disable no-unused-vars */ function lpRewardsRemoveLiquidityNormalization( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256) { return _amount; } /* solhint-enable no-unused-vars */ /// @dev formula may add a decreasing rewards if locking end is near when adding liquidity /// @param _bond , bonding share /// @param _amount , amount of LP tokens /// @notice rewards = _amount; // solhint-disable-block no-unused-vars /* solhint-disable no-unused-vars */ function lpRewardsAddLiquidityNormalization( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256) { return _amount; } /* solhint-enable no-unused-vars */ /// @dev formula to calculate the corrected amount to withdraw based on the proportion of /// lp deposited against actual LP token on thge bonding contract /// @param _totalLpDeposited , Total amount of LP deposited by users /// @param _bondingLpBalance , actual bonding contract LP tokens balance minus lp rewards /// @param _amount , amount of LP tokens /// @notice corrected_amount = amount * ( bondingLpBalance / totalLpDeposited) /// if there is more or the same amount of LP than deposited then do nothing function correctedAmountToWithdraw( uint256 _totalLpDeposited, uint256 _bondingLpBalance, uint256 _amount ) public pure returns (uint256) { if (_bondingLpBalance < _totalLpDeposited && _bondingLpBalance > 0) { // if there is less LP token inside the bonding contract that what have been deposited // we have to reduce proportionnaly the lp amount to withdraw return _amount .fromUInt() .mul(_bondingLpBalance.fromUInt()) .div(_totalLpDeposited.fromUInt()) .toUInt(); } return _amount; } }
lpRewardsRemoveLiquidityNormalization
function lpRewardsRemoveLiquidityNormalization( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256) { return _amount; }
/* solhint-disable no-unused-vars */
Comment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1069, 1292 ] }
3,322
BondingShareV2
contracts/BondingFormulas.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingFormulas
contract BondingFormulas { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; uint256 public constant ONE = uint256(1 ether); // 18 decimals /// @dev formula UBQ Rights corresponding to a bonding shares LP amount /// @param _bond , bonding share /// @param _amount , amount of LP tokens /// @notice shares = (bond.shares * _amount ) / bond.lpAmount ; function sharesForLP( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256 _uLP) { bytes16 a = _shareInfo[0].fromUInt(); // shares amount bytes16 v = _amount.fromUInt(); bytes16 t = _bond.lpAmount.fromUInt(); _uLP = a.mul(v).div(t).toUInt(); } /// @dev formula may add a decreasing rewards if locking end is near when removing liquidity /// @param _bond , bonding share /// @param _amount , amount of LP tokens /// @notice rewards = _amount; // solhint-disable-block no-unused-vars /* solhint-disable no-unused-vars */ function lpRewardsRemoveLiquidityNormalization( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256) { return _amount; } /* solhint-enable no-unused-vars */ /// @dev formula may add a decreasing rewards if locking end is near when adding liquidity /// @param _bond , bonding share /// @param _amount , amount of LP tokens /// @notice rewards = _amount; // solhint-disable-block no-unused-vars /* solhint-disable no-unused-vars */ function lpRewardsAddLiquidityNormalization( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256) { return _amount; } /* solhint-enable no-unused-vars */ /// @dev formula to calculate the corrected amount to withdraw based on the proportion of /// lp deposited against actual LP token on thge bonding contract /// @param _totalLpDeposited , Total amount of LP deposited by users /// @param _bondingLpBalance , actual bonding contract LP tokens balance minus lp rewards /// @param _amount , amount of LP tokens /// @notice corrected_amount = amount * ( bondingLpBalance / totalLpDeposited) /// if there is more or the same amount of LP than deposited then do nothing function correctedAmountToWithdraw( uint256 _totalLpDeposited, uint256 _bondingLpBalance, uint256 _amount ) public pure returns (uint256) { if (_bondingLpBalance < _totalLpDeposited && _bondingLpBalance > 0) { // if there is less LP token inside the bonding contract that what have been deposited // we have to reduce proportionnaly the lp amount to withdraw return _amount .fromUInt() .mul(_bondingLpBalance.fromUInt()) .div(_totalLpDeposited.fromUInt()) .toUInt(); } return _amount; } }
lpRewardsAddLiquidityNormalization
function lpRewardsAddLiquidityNormalization( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256) { return _amount; }
/* solhint-disable no-unused-vars */
Comment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1632, 1852 ] }
3,323
BondingShareV2
contracts/BondingFormulas.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
BondingFormulas
contract BondingFormulas { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; uint256 public constant ONE = uint256(1 ether); // 18 decimals /// @dev formula UBQ Rights corresponding to a bonding shares LP amount /// @param _bond , bonding share /// @param _amount , amount of LP tokens /// @notice shares = (bond.shares * _amount ) / bond.lpAmount ; function sharesForLP( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256 _uLP) { bytes16 a = _shareInfo[0].fromUInt(); // shares amount bytes16 v = _amount.fromUInt(); bytes16 t = _bond.lpAmount.fromUInt(); _uLP = a.mul(v).div(t).toUInt(); } /// @dev formula may add a decreasing rewards if locking end is near when removing liquidity /// @param _bond , bonding share /// @param _amount , amount of LP tokens /// @notice rewards = _amount; // solhint-disable-block no-unused-vars /* solhint-disable no-unused-vars */ function lpRewardsRemoveLiquidityNormalization( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256) { return _amount; } /* solhint-enable no-unused-vars */ /// @dev formula may add a decreasing rewards if locking end is near when adding liquidity /// @param _bond , bonding share /// @param _amount , amount of LP tokens /// @notice rewards = _amount; // solhint-disable-block no-unused-vars /* solhint-disable no-unused-vars */ function lpRewardsAddLiquidityNormalization( BondingShareV2.Bond memory _bond, uint256[2] memory _shareInfo, uint256 _amount ) public pure returns (uint256) { return _amount; } /* solhint-enable no-unused-vars */ /// @dev formula to calculate the corrected amount to withdraw based on the proportion of /// lp deposited against actual LP token on thge bonding contract /// @param _totalLpDeposited , Total amount of LP deposited by users /// @param _bondingLpBalance , actual bonding contract LP tokens balance minus lp rewards /// @param _amount , amount of LP tokens /// @notice corrected_amount = amount * ( bondingLpBalance / totalLpDeposited) /// if there is more or the same amount of LP than deposited then do nothing function correctedAmountToWithdraw( uint256 _totalLpDeposited, uint256 _bondingLpBalance, uint256 _amount ) public pure returns (uint256) { if (_bondingLpBalance < _totalLpDeposited && _bondingLpBalance > 0) { // if there is less LP token inside the bonding contract that what have been deposited // we have to reduce proportionnaly the lp amount to withdraw return _amount .fromUInt() .mul(_bondingLpBalance.fromUInt()) .div(_totalLpDeposited.fromUInt()) .toUInt(); } return _amount; } }
correctedAmountToWithdraw
function correctedAmountToWithdraw( uint256 _totalLpDeposited, uint256 _bondingLpBalance, uint256 _amount ) public pure returns (uint256) { if (_bondingLpBalance < _totalLpDeposited && _bondingLpBalance > 0) { // if there is less LP token inside the bonding contract that what have been deposited // we have to reduce proportionnaly the lp amount to withdraw return _amount .fromUInt() .mul(_bondingLpBalance.fromUInt()) .div(_totalLpDeposited.fromUInt()) .toUInt(); } return _amount; }
/// @dev formula to calculate the corrected amount to withdraw based on the proportion of /// lp deposited against actual LP token on thge bonding contract /// @param _totalLpDeposited , Total amount of LP deposited by users /// @param _bondingLpBalance , actual bonding contract LP tokens balance minus lp rewards /// @param _amount , amount of LP tokens /// @notice corrected_amount = amount * ( bondingLpBalance / totalLpDeposited) /// if there is more or the same amount of LP than deposited then do nothing
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 2448, 3126 ] }
3,324
BondingShareV2
contracts/interfaces/ISushiMasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ISushiMasterChef
interface ISushiMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() external; // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) external; // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external; // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; // Returns the address of the current owner. function owner() external view returns (address); // Info of each pool. function userInfo(uint256 pid, address user) external view returns (ISushiMasterChef.UserInfo memory); // SUSHI tokens created per block. function sushiPerBlock() external view returns (uint256); // Info of each pool. function poolInfo(uint256 pid) external view returns (ISushiMasterChef.PoolInfo memory); // Total allocation poitns. Must be the sum of all allocation points in all pools. function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256); }
withdraw
function withdraw(uint256 _pid, uint256 _amount) external;
// Withdraw LP tokens from MasterChef.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 916, 978 ] }
3,325
BondingShareV2
contracts/interfaces/ISushiMasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ISushiMasterChef
interface ISushiMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() external; // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) external; // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external; // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; // Returns the address of the current owner. function owner() external view returns (address); // Info of each pool. function userInfo(uint256 pid, address user) external view returns (ISushiMasterChef.UserInfo memory); // SUSHI tokens created per block. function sushiPerBlock() external view returns (uint256); // Info of each pool. function poolInfo(uint256 pid) external view returns (ISushiMasterChef.PoolInfo memory); // Total allocation poitns. Must be the sum of all allocation points in all pools. function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256); }
massUpdatePools
function massUpdatePools() external;
// Update reward vairables for all pools. Be careful of gas spending!
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1054, 1094 ] }
3,326
BondingShareV2
contracts/interfaces/ISushiMasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ISushiMasterChef
interface ISushiMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() external; // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) external; // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external; // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; // Returns the address of the current owner. function owner() external view returns (address); // Info of each pool. function userInfo(uint256 pid, address user) external view returns (ISushiMasterChef.UserInfo memory); // SUSHI tokens created per block. function sushiPerBlock() external view returns (uint256); // Info of each pool. function poolInfo(uint256 pid) external view returns (ISushiMasterChef.PoolInfo memory); // Total allocation poitns. Must be the sum of all allocation points in all pools. function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256); }
updatePool
function updatePool(uint256 _pid) external;
// Update reward variables of the given pool to be up-to-date.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1163, 1210 ] }
3,327
BondingShareV2
contracts/interfaces/ISushiMasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ISushiMasterChef
interface ISushiMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() external; // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) external; // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external; // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; // Returns the address of the current owner. function owner() external view returns (address); // Info of each pool. function userInfo(uint256 pid, address user) external view returns (ISushiMasterChef.UserInfo memory); // SUSHI tokens created per block. function sushiPerBlock() external view returns (uint256); // Info of each pool. function poolInfo(uint256 pid) external view returns (ISushiMasterChef.PoolInfo memory); // Total allocation poitns. Must be the sum of all allocation points in all pools. function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256); }
add
function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external;
// Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1371, 1483 ] }
3,328
BondingShareV2
contracts/interfaces/ISushiMasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ISushiMasterChef
interface ISushiMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() external; // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) external; // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external; // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; // Returns the address of the current owner. function owner() external view returns (address); // Info of each pool. function userInfo(uint256 pid, address user) external view returns (ISushiMasterChef.UserInfo memory); // SUSHI tokens created per block. function sushiPerBlock() external view returns (uint256); // Info of each pool. function poolInfo(uint256 pid) external view returns (ISushiMasterChef.PoolInfo memory); // Total allocation poitns. Must be the sum of all allocation points in all pools. function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256); }
set
function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external;
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1573, 1682 ] }
3,329
BondingShareV2
contracts/interfaces/ISushiMasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ISushiMasterChef
interface ISushiMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() external; // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) external; // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external; // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; // Returns the address of the current owner. function owner() external view returns (address); // Info of each pool. function userInfo(uint256 pid, address user) external view returns (ISushiMasterChef.UserInfo memory); // SUSHI tokens created per block. function sushiPerBlock() external view returns (uint256); // Info of each pool. function poolInfo(uint256 pid) external view returns (ISushiMasterChef.PoolInfo memory); // Total allocation poitns. Must be the sum of all allocation points in all pools. function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256); }
owner
function owner() external view returns (address);
// Returns the address of the current owner.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1733, 1786 ] }
3,330
BondingShareV2
contracts/interfaces/ISushiMasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ISushiMasterChef
interface ISushiMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() external; // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) external; // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external; // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; // Returns the address of the current owner. function owner() external view returns (address); // Info of each pool. function userInfo(uint256 pid, address user) external view returns (ISushiMasterChef.UserInfo memory); // SUSHI tokens created per block. function sushiPerBlock() external view returns (uint256); // Info of each pool. function poolInfo(uint256 pid) external view returns (ISushiMasterChef.PoolInfo memory); // Total allocation poitns. Must be the sum of all allocation points in all pools. function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256); }
userInfo
function userInfo(uint256 pid, address user) external view returns (ISushiMasterChef.UserInfo memory);
// Info of each pool.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1814, 1944 ] }
3,331
BondingShareV2
contracts/interfaces/ISushiMasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ISushiMasterChef
interface ISushiMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() external; // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) external; // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external; // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; // Returns the address of the current owner. function owner() external view returns (address); // Info of each pool. function userInfo(uint256 pid, address user) external view returns (ISushiMasterChef.UserInfo memory); // SUSHI tokens created per block. function sushiPerBlock() external view returns (uint256); // Info of each pool. function poolInfo(uint256 pid) external view returns (ISushiMasterChef.PoolInfo memory); // Total allocation poitns. Must be the sum of all allocation points in all pools. function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256); }
sushiPerBlock
function sushiPerBlock() external view returns (uint256);
// SUSHI tokens created per block.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1985, 2046 ] }
3,332
BondingShareV2
contracts/interfaces/ISushiMasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ISushiMasterChef
interface ISushiMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() external; // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) external; // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external; // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; // Returns the address of the current owner. function owner() external view returns (address); // Info of each pool. function userInfo(uint256 pid, address user) external view returns (ISushiMasterChef.UserInfo memory); // SUSHI tokens created per block. function sushiPerBlock() external view returns (uint256); // Info of each pool. function poolInfo(uint256 pid) external view returns (ISushiMasterChef.PoolInfo memory); // Total allocation poitns. Must be the sum of all allocation points in all pools. function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256); }
poolInfo
function poolInfo(uint256 pid) external view returns (ISushiMasterChef.PoolInfo memory);
// Info of each pool.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 2074, 2190 ] }
3,333
BondingShareV2
contracts/interfaces/ISushiMasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ISushiMasterChef
interface ISushiMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() external; // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) external; // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external; // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; // Returns the address of the current owner. function owner() external view returns (address); // Info of each pool. function userInfo(uint256 pid, address user) external view returns (ISushiMasterChef.UserInfo memory); // SUSHI tokens created per block. function sushiPerBlock() external view returns (uint256); // Info of each pool. function poolInfo(uint256 pid) external view returns (ISushiMasterChef.PoolInfo memory); // Total allocation poitns. Must be the sum of all allocation points in all pools. function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256); }
totalAllocPoint
function totalAllocPoint() external view returns (uint256);
// Total allocation poitns. Must be the sum of all allocation points in all pools.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 2279, 2342 ] }
3,334
BondingShareV2
contracts/interfaces/ISushiMasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ISushiMasterChef
interface ISushiMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() external; // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) external; // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external; // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; // Returns the address of the current owner. function owner() external view returns (address); // Info of each pool. function userInfo(uint256 pid, address user) external view returns (ISushiMasterChef.UserInfo memory); // SUSHI tokens created per block. function sushiPerBlock() external view returns (uint256); // Info of each pool. function poolInfo(uint256 pid) external view returns (ISushiMasterChef.PoolInfo memory); // Total allocation poitns. Must be the sum of all allocation points in all pools. function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256); }
pendingSushi
function pendingSushi(uint256 _pid, address _user) external view returns (uint256);
// View function to see pending SUSHIs on frontend.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 2460, 2571 ] }
3,335
BondingShareV2
contracts/DebtCoupon.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
DebtCoupon
contract DebtCoupon is ERC1155Ubiquity { using StructuredLinkedList for StructuredLinkedList.List; //not public as if called externally can give inaccurate value. see method uint256 private _totalOutstandingDebt; //represents tokenSupply of each expiry (since 1155 doesnt have this) mapping(uint256 => uint256) private _tokenSupplies; //ordered list of coupon expiries StructuredLinkedList.List private _sortedBlockNumbers; event MintedCoupons(address recipient, uint256 expiryBlock, uint256 amount); event BurnedCoupons( address couponHolder, uint256 expiryBlock, uint256 amount ); modifier onlyCouponManager() { require( manager.hasRole(manager.COUPON_MANAGER_ROLE(), msg.sender), "Caller is not a coupon manager" ); _; } //@dev URI param is if we want to add an off-chain meta data uri associated with this contract constructor(address _manager) ERC1155Ubiquity(_manager, "URI") { manager = UbiquityAlgorithmicDollarManager(_manager); _totalOutstandingDebt = 0; } /// @notice Mint an amount of coupons expiring at a certain block for a certain recipient /// @param amount amount of tokens to mint /// @param expiryBlockNumber the expiration block number of the coupons to mint function mintCoupons( address recipient, uint256 amount, uint256 expiryBlockNumber ) public onlyCouponManager { mint(recipient, expiryBlockNumber, amount, ""); emit MintedCoupons(recipient, expiryBlockNumber, amount); //insert new relevant block number if it doesnt exist in our list // (linkedlist implementation wont insert if dupe) _sortedBlockNumbers.pushBack(expiryBlockNumber); //update the total supply for that expiry and total outstanding debt _tokenSupplies[expiryBlockNumber] = _tokenSupplies[expiryBlockNumber] + (amount); _totalOutstandingDebt = _totalOutstandingDebt + (amount); } /// @notice Burn an amount of coupons expiring at a certain block from /// a certain holder's balance /// @param couponOwner the owner of those coupons /// @param amount amount of tokens to burn /// @param expiryBlockNumber the expiration block number of the coupons to burn function burnCoupons( address couponOwner, uint256 amount, uint256 expiryBlockNumber ) public onlyCouponManager { require( balanceOf(couponOwner, expiryBlockNumber) >= amount, "Coupon owner not enough coupons" ); burn(couponOwner, expiryBlockNumber, amount); emit BurnedCoupons(couponOwner, expiryBlockNumber, amount); //update the total supply for that expiry and total outstanding debt _tokenSupplies[expiryBlockNumber] = _tokenSupplies[expiryBlockNumber] - (amount); _totalOutstandingDebt = _totalOutstandingDebt - (amount); } /// @notice Should be called prior to any state changing functions. // Updates debt according to current block number function updateTotalDebt() public { bool reachedEndOfExpiredKeys = false; uint256 currentBlockNumber = _sortedBlockNumbers.popFront(); //if list is empty, currentBlockNumber will be 0 while (!reachedEndOfExpiredKeys && currentBlockNumber != 0) { if (currentBlockNumber > block.number) { //put the key back in since we popped, and end loop _sortedBlockNumbers.pushFront(currentBlockNumber); reachedEndOfExpiredKeys = true; } else { //update tally and remove key from blocks and map _totalOutstandingDebt = _totalOutstandingDebt - (_tokenSupplies[currentBlockNumber]); delete _tokenSupplies[currentBlockNumber]; _sortedBlockNumbers.remove(currentBlockNumber); } currentBlockNumber = _sortedBlockNumbers.popFront(); } } /// @notice Returns outstanding debt by fetching current tally and removing any expired debt function getTotalOutstandingDebt() public view returns (uint256) { uint256 outstandingDebt = _totalOutstandingDebt; bool reachedEndOfExpiredKeys = false; (, uint256 currentBlockNumber) = _sortedBlockNumbers.getNextNode(0); while (!reachedEndOfExpiredKeys && currentBlockNumber != 0) { if (currentBlockNumber > block.number) { reachedEndOfExpiredKeys = true; } else { outstandingDebt = outstandingDebt - (_tokenSupplies[currentBlockNumber]); } (, currentBlockNumber) = _sortedBlockNumbers.getNextNode( currentBlockNumber ); } return outstandingDebt; } }
/// @title A coupon redeemable for dollars with an expiry block number /// @notice An ERC1155 where the token ID is the expiry block number /// @dev Implements ERC1155 so receiving contracts must implement IERC1155Receiver
NatSpecSingleLine
mintCoupons
function mintCoupons( address recipient, uint256 amount, uint256 expiryBlockNumber ) public onlyCouponManager { mint(recipient, expiryBlockNumber, amount, ""); emit MintedCoupons(recipient, expiryBlockNumber, amount); //insert new relevant block number if it doesnt exist in our list // (linkedlist implementation wont insert if dupe) _sortedBlockNumbers.pushBack(expiryBlockNumber); //update the total supply for that expiry and total outstanding debt _tokenSupplies[expiryBlockNumber] = _tokenSupplies[expiryBlockNumber] + (amount); _totalOutstandingDebt = _totalOutstandingDebt + (amount); }
/// @notice Mint an amount of coupons expiring at a certain block for a certain recipient /// @param amount amount of tokens to mint /// @param expiryBlockNumber the expiration block number of the coupons to mint
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1348, 2068 ] }
3,336
BondingShareV2
contracts/DebtCoupon.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
DebtCoupon
contract DebtCoupon is ERC1155Ubiquity { using StructuredLinkedList for StructuredLinkedList.List; //not public as if called externally can give inaccurate value. see method uint256 private _totalOutstandingDebt; //represents tokenSupply of each expiry (since 1155 doesnt have this) mapping(uint256 => uint256) private _tokenSupplies; //ordered list of coupon expiries StructuredLinkedList.List private _sortedBlockNumbers; event MintedCoupons(address recipient, uint256 expiryBlock, uint256 amount); event BurnedCoupons( address couponHolder, uint256 expiryBlock, uint256 amount ); modifier onlyCouponManager() { require( manager.hasRole(manager.COUPON_MANAGER_ROLE(), msg.sender), "Caller is not a coupon manager" ); _; } //@dev URI param is if we want to add an off-chain meta data uri associated with this contract constructor(address _manager) ERC1155Ubiquity(_manager, "URI") { manager = UbiquityAlgorithmicDollarManager(_manager); _totalOutstandingDebt = 0; } /// @notice Mint an amount of coupons expiring at a certain block for a certain recipient /// @param amount amount of tokens to mint /// @param expiryBlockNumber the expiration block number of the coupons to mint function mintCoupons( address recipient, uint256 amount, uint256 expiryBlockNumber ) public onlyCouponManager { mint(recipient, expiryBlockNumber, amount, ""); emit MintedCoupons(recipient, expiryBlockNumber, amount); //insert new relevant block number if it doesnt exist in our list // (linkedlist implementation wont insert if dupe) _sortedBlockNumbers.pushBack(expiryBlockNumber); //update the total supply for that expiry and total outstanding debt _tokenSupplies[expiryBlockNumber] = _tokenSupplies[expiryBlockNumber] + (amount); _totalOutstandingDebt = _totalOutstandingDebt + (amount); } /// @notice Burn an amount of coupons expiring at a certain block from /// a certain holder's balance /// @param couponOwner the owner of those coupons /// @param amount amount of tokens to burn /// @param expiryBlockNumber the expiration block number of the coupons to burn function burnCoupons( address couponOwner, uint256 amount, uint256 expiryBlockNumber ) public onlyCouponManager { require( balanceOf(couponOwner, expiryBlockNumber) >= amount, "Coupon owner not enough coupons" ); burn(couponOwner, expiryBlockNumber, amount); emit BurnedCoupons(couponOwner, expiryBlockNumber, amount); //update the total supply for that expiry and total outstanding debt _tokenSupplies[expiryBlockNumber] = _tokenSupplies[expiryBlockNumber] - (amount); _totalOutstandingDebt = _totalOutstandingDebt - (amount); } /// @notice Should be called prior to any state changing functions. // Updates debt according to current block number function updateTotalDebt() public { bool reachedEndOfExpiredKeys = false; uint256 currentBlockNumber = _sortedBlockNumbers.popFront(); //if list is empty, currentBlockNumber will be 0 while (!reachedEndOfExpiredKeys && currentBlockNumber != 0) { if (currentBlockNumber > block.number) { //put the key back in since we popped, and end loop _sortedBlockNumbers.pushFront(currentBlockNumber); reachedEndOfExpiredKeys = true; } else { //update tally and remove key from blocks and map _totalOutstandingDebt = _totalOutstandingDebt - (_tokenSupplies[currentBlockNumber]); delete _tokenSupplies[currentBlockNumber]; _sortedBlockNumbers.remove(currentBlockNumber); } currentBlockNumber = _sortedBlockNumbers.popFront(); } } /// @notice Returns outstanding debt by fetching current tally and removing any expired debt function getTotalOutstandingDebt() public view returns (uint256) { uint256 outstandingDebt = _totalOutstandingDebt; bool reachedEndOfExpiredKeys = false; (, uint256 currentBlockNumber) = _sortedBlockNumbers.getNextNode(0); while (!reachedEndOfExpiredKeys && currentBlockNumber != 0) { if (currentBlockNumber > block.number) { reachedEndOfExpiredKeys = true; } else { outstandingDebt = outstandingDebt - (_tokenSupplies[currentBlockNumber]); } (, currentBlockNumber) = _sortedBlockNumbers.getNextNode( currentBlockNumber ); } return outstandingDebt; } }
/// @title A coupon redeemable for dollars with an expiry block number /// @notice An ERC1155 where the token ID is the expiry block number /// @dev Implements ERC1155 so receiving contracts must implement IERC1155Receiver
NatSpecSingleLine
burnCoupons
function burnCoupons( address couponOwner, uint256 amount, uint256 expiryBlockNumber ) public onlyCouponManager { require( balanceOf(couponOwner, expiryBlockNumber) >= amount, "Coupon owner not enough coupons" ); burn(couponOwner, expiryBlockNumber, amount); emit BurnedCoupons(couponOwner, expiryBlockNumber, amount); //update the total supply for that expiry and total outstanding debt _tokenSupplies[expiryBlockNumber] = _tokenSupplies[expiryBlockNumber] - (amount); _totalOutstandingDebt = _totalOutstandingDebt - (amount); }
/// @notice Burn an amount of coupons expiring at a certain block from /// a certain holder's balance /// @param couponOwner the owner of those coupons /// @param amount amount of tokens to burn /// @param expiryBlockNumber the expiration block number of the coupons to burn
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 2365, 3035 ] }
3,337
BondingShareV2
contracts/DebtCoupon.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
DebtCoupon
contract DebtCoupon is ERC1155Ubiquity { using StructuredLinkedList for StructuredLinkedList.List; //not public as if called externally can give inaccurate value. see method uint256 private _totalOutstandingDebt; //represents tokenSupply of each expiry (since 1155 doesnt have this) mapping(uint256 => uint256) private _tokenSupplies; //ordered list of coupon expiries StructuredLinkedList.List private _sortedBlockNumbers; event MintedCoupons(address recipient, uint256 expiryBlock, uint256 amount); event BurnedCoupons( address couponHolder, uint256 expiryBlock, uint256 amount ); modifier onlyCouponManager() { require( manager.hasRole(manager.COUPON_MANAGER_ROLE(), msg.sender), "Caller is not a coupon manager" ); _; } //@dev URI param is if we want to add an off-chain meta data uri associated with this contract constructor(address _manager) ERC1155Ubiquity(_manager, "URI") { manager = UbiquityAlgorithmicDollarManager(_manager); _totalOutstandingDebt = 0; } /// @notice Mint an amount of coupons expiring at a certain block for a certain recipient /// @param amount amount of tokens to mint /// @param expiryBlockNumber the expiration block number of the coupons to mint function mintCoupons( address recipient, uint256 amount, uint256 expiryBlockNumber ) public onlyCouponManager { mint(recipient, expiryBlockNumber, amount, ""); emit MintedCoupons(recipient, expiryBlockNumber, amount); //insert new relevant block number if it doesnt exist in our list // (linkedlist implementation wont insert if dupe) _sortedBlockNumbers.pushBack(expiryBlockNumber); //update the total supply for that expiry and total outstanding debt _tokenSupplies[expiryBlockNumber] = _tokenSupplies[expiryBlockNumber] + (amount); _totalOutstandingDebt = _totalOutstandingDebt + (amount); } /// @notice Burn an amount of coupons expiring at a certain block from /// a certain holder's balance /// @param couponOwner the owner of those coupons /// @param amount amount of tokens to burn /// @param expiryBlockNumber the expiration block number of the coupons to burn function burnCoupons( address couponOwner, uint256 amount, uint256 expiryBlockNumber ) public onlyCouponManager { require( balanceOf(couponOwner, expiryBlockNumber) >= amount, "Coupon owner not enough coupons" ); burn(couponOwner, expiryBlockNumber, amount); emit BurnedCoupons(couponOwner, expiryBlockNumber, amount); //update the total supply for that expiry and total outstanding debt _tokenSupplies[expiryBlockNumber] = _tokenSupplies[expiryBlockNumber] - (amount); _totalOutstandingDebt = _totalOutstandingDebt - (amount); } /// @notice Should be called prior to any state changing functions. // Updates debt according to current block number function updateTotalDebt() public { bool reachedEndOfExpiredKeys = false; uint256 currentBlockNumber = _sortedBlockNumbers.popFront(); //if list is empty, currentBlockNumber will be 0 while (!reachedEndOfExpiredKeys && currentBlockNumber != 0) { if (currentBlockNumber > block.number) { //put the key back in since we popped, and end loop _sortedBlockNumbers.pushFront(currentBlockNumber); reachedEndOfExpiredKeys = true; } else { //update tally and remove key from blocks and map _totalOutstandingDebt = _totalOutstandingDebt - (_tokenSupplies[currentBlockNumber]); delete _tokenSupplies[currentBlockNumber]; _sortedBlockNumbers.remove(currentBlockNumber); } currentBlockNumber = _sortedBlockNumbers.popFront(); } } /// @notice Returns outstanding debt by fetching current tally and removing any expired debt function getTotalOutstandingDebt() public view returns (uint256) { uint256 outstandingDebt = _totalOutstandingDebt; bool reachedEndOfExpiredKeys = false; (, uint256 currentBlockNumber) = _sortedBlockNumbers.getNextNode(0); while (!reachedEndOfExpiredKeys && currentBlockNumber != 0) { if (currentBlockNumber > block.number) { reachedEndOfExpiredKeys = true; } else { outstandingDebt = outstandingDebt - (_tokenSupplies[currentBlockNumber]); } (, currentBlockNumber) = _sortedBlockNumbers.getNextNode( currentBlockNumber ); } return outstandingDebt; } }
/// @title A coupon redeemable for dollars with an expiry block number /// @notice An ERC1155 where the token ID is the expiry block number /// @dev Implements ERC1155 so receiving contracts must implement IERC1155Receiver
NatSpecSingleLine
updateTotalDebt
function updateTotalDebt() public { bool reachedEndOfExpiredKeys = false; uint256 currentBlockNumber = _sortedBlockNumbers.popFront(); //if list is empty, currentBlockNumber will be 0 while (!reachedEndOfExpiredKeys && currentBlockNumber != 0) { if (currentBlockNumber > block.number) { //put the key back in since we popped, and end loop _sortedBlockNumbers.pushFront(currentBlockNumber); reachedEndOfExpiredKeys = true; } else { //update tally and remove key from blocks and map _totalOutstandingDebt = _totalOutstandingDebt - (_tokenSupplies[currentBlockNumber]); delete _tokenSupplies[currentBlockNumber]; _sortedBlockNumbers.remove(currentBlockNumber); } currentBlockNumber = _sortedBlockNumbers.popFront(); } }
// Updates debt according to current block number
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3163, 4128 ] }
3,338
BondingShareV2
contracts/DebtCoupon.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
DebtCoupon
contract DebtCoupon is ERC1155Ubiquity { using StructuredLinkedList for StructuredLinkedList.List; //not public as if called externally can give inaccurate value. see method uint256 private _totalOutstandingDebt; //represents tokenSupply of each expiry (since 1155 doesnt have this) mapping(uint256 => uint256) private _tokenSupplies; //ordered list of coupon expiries StructuredLinkedList.List private _sortedBlockNumbers; event MintedCoupons(address recipient, uint256 expiryBlock, uint256 amount); event BurnedCoupons( address couponHolder, uint256 expiryBlock, uint256 amount ); modifier onlyCouponManager() { require( manager.hasRole(manager.COUPON_MANAGER_ROLE(), msg.sender), "Caller is not a coupon manager" ); _; } //@dev URI param is if we want to add an off-chain meta data uri associated with this contract constructor(address _manager) ERC1155Ubiquity(_manager, "URI") { manager = UbiquityAlgorithmicDollarManager(_manager); _totalOutstandingDebt = 0; } /// @notice Mint an amount of coupons expiring at a certain block for a certain recipient /// @param amount amount of tokens to mint /// @param expiryBlockNumber the expiration block number of the coupons to mint function mintCoupons( address recipient, uint256 amount, uint256 expiryBlockNumber ) public onlyCouponManager { mint(recipient, expiryBlockNumber, amount, ""); emit MintedCoupons(recipient, expiryBlockNumber, amount); //insert new relevant block number if it doesnt exist in our list // (linkedlist implementation wont insert if dupe) _sortedBlockNumbers.pushBack(expiryBlockNumber); //update the total supply for that expiry and total outstanding debt _tokenSupplies[expiryBlockNumber] = _tokenSupplies[expiryBlockNumber] + (amount); _totalOutstandingDebt = _totalOutstandingDebt + (amount); } /// @notice Burn an amount of coupons expiring at a certain block from /// a certain holder's balance /// @param couponOwner the owner of those coupons /// @param amount amount of tokens to burn /// @param expiryBlockNumber the expiration block number of the coupons to burn function burnCoupons( address couponOwner, uint256 amount, uint256 expiryBlockNumber ) public onlyCouponManager { require( balanceOf(couponOwner, expiryBlockNumber) >= amount, "Coupon owner not enough coupons" ); burn(couponOwner, expiryBlockNumber, amount); emit BurnedCoupons(couponOwner, expiryBlockNumber, amount); //update the total supply for that expiry and total outstanding debt _tokenSupplies[expiryBlockNumber] = _tokenSupplies[expiryBlockNumber] - (amount); _totalOutstandingDebt = _totalOutstandingDebt - (amount); } /// @notice Should be called prior to any state changing functions. // Updates debt according to current block number function updateTotalDebt() public { bool reachedEndOfExpiredKeys = false; uint256 currentBlockNumber = _sortedBlockNumbers.popFront(); //if list is empty, currentBlockNumber will be 0 while (!reachedEndOfExpiredKeys && currentBlockNumber != 0) { if (currentBlockNumber > block.number) { //put the key back in since we popped, and end loop _sortedBlockNumbers.pushFront(currentBlockNumber); reachedEndOfExpiredKeys = true; } else { //update tally and remove key from blocks and map _totalOutstandingDebt = _totalOutstandingDebt - (_tokenSupplies[currentBlockNumber]); delete _tokenSupplies[currentBlockNumber]; _sortedBlockNumbers.remove(currentBlockNumber); } currentBlockNumber = _sortedBlockNumbers.popFront(); } } /// @notice Returns outstanding debt by fetching current tally and removing any expired debt function getTotalOutstandingDebt() public view returns (uint256) { uint256 outstandingDebt = _totalOutstandingDebt; bool reachedEndOfExpiredKeys = false; (, uint256 currentBlockNumber) = _sortedBlockNumbers.getNextNode(0); while (!reachedEndOfExpiredKeys && currentBlockNumber != 0) { if (currentBlockNumber > block.number) { reachedEndOfExpiredKeys = true; } else { outstandingDebt = outstandingDebt - (_tokenSupplies[currentBlockNumber]); } (, currentBlockNumber) = _sortedBlockNumbers.getNextNode( currentBlockNumber ); } return outstandingDebt; } }
/// @title A coupon redeemable for dollars with an expiry block number /// @notice An ERC1155 where the token ID is the expiry block number /// @dev Implements ERC1155 so receiving contracts must implement IERC1155Receiver
NatSpecSingleLine
getTotalOutstandingDebt
function getTotalOutstandingDebt() public view returns (uint256) { uint256 outstandingDebt = _totalOutstandingDebt; bool reachedEndOfExpiredKeys = false; (, uint256 currentBlockNumber) = _sortedBlockNumbers.getNextNode(0); while (!reachedEndOfExpiredKeys && currentBlockNumber != 0) { if (currentBlockNumber > block.number) { reachedEndOfExpiredKeys = true; } else { outstandingDebt = outstandingDebt - (_tokenSupplies[currentBlockNumber]); } (, currentBlockNumber) = _sortedBlockNumbers.getNextNode( currentBlockNumber ); } return outstandingDebt; }
/// @notice Returns outstanding debt by fetching current tally and removing any expired debt
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 4227, 4983 ] }
3,339
BondingShareV2
contracts/UbiquityAutoRedeem.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
UbiquityAutoRedeem
contract UbiquityAutoRedeem is ERC20Ubiquity { constructor(address _manager) ERC20Ubiquity(_manager, "Ubiquity Auto Redeem", "uAR") {} // solhint-disable-line no-empty-blocks /// @notice raise capital in form of uAR (only redeemable when uAD > 1$) /// @param amount the amount to be minted /// @dev you should be minter to call that function function raiseCapital(uint256 amount) external { address treasuryAddress = manager.treasuryAddress(); mint(treasuryAddress, amount); } }
raiseCapital
function raiseCapital(uint256 amount) external { address treasuryAddress = manager.treasuryAddress(); mint(treasuryAddress, amount); }
/// @notice raise capital in form of uAR (only redeemable when uAD > 1$) /// @param amount the amount to be minted /// @dev you should be minter to call that function
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 371, 529 ] }
3,340
BondingShareV2
contracts/interfaces/IMasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
IMasterChef
interface IMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accuGOVPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); function deposit(uint256 _amount, address sender) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _amount, address sender) external; // View function to see pending SUSHIs on frontend. function pendingUGOV(address _user) external view returns (uint256); }
withdraw
function withdraw(uint256 _amount, address sender) external;
// Withdraw LP tokens from MasterChef.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 615, 679 ] }
3,341
BondingShareV2
contracts/interfaces/IMasterChef.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
IMasterChef
interface IMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accuGOVPerShare; // Accumulated SUSHI per share, times 1e12. See below. } event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); function deposit(uint256 _amount, address sender) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _amount, address sender) external; // View function to see pending SUSHIs on frontend. function pendingUGOV(address _user) external view returns (uint256); }
pendingUGOV
function pendingUGOV(address _user) external view returns (uint256);
// View function to see pending SUSHIs on frontend.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 737, 809 ] }
3,342
BondingShareV2
contracts/DollarMintingCalculator.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
DollarMintingCalculator
contract DollarMintingCalculator is IDollarMintingCalculator { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; bytes16 private immutable _one = (uint256(1 ether)).fromUInt(); UbiquityAlgorithmicDollarManager public manager; /// @param _manager the address of the manager contract so we can fetch variables constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } /// @notice returns (TWAP_PRICE -1) * UAD_Total_Supply function getDollarsToMint() external view override returns (uint256) { TWAPOracle oracle = TWAPOracle(manager.twapOracleAddress()); uint256 twapPrice = oracle.consult(manager.dollarTokenAddress()); require(twapPrice > 1, "DollarMintingCalculator: not > 1"); return twapPrice .fromUInt() .sub(_one) .mul( ( IERC20(manager.dollarTokenAddress()) .totalSupply() .fromUInt() .div(_one) ) ) .toUInt(); } }
/// @title A mock coupon calculator that always returns a constant
NatSpecSingleLine
getDollarsToMint
function getDollarsToMint() external view override returns (uint256) { TWAPOracle oracle = TWAPOracle(manager.twapOracleAddress()); uint256 twapPrice = oracle.consult(manager.dollarTokenAddress()); require(twapPrice > 1, "DollarMintingCalculator: not > 1"); return twapPrice .fromUInt() .sub(_one) .mul( ( IERC20(manager.dollarTokenAddress()) .totalSupply() .fromUInt() .div(_one) ) ) .toUInt(); }
/// @notice returns (TWAP_PRICE -1) * UAD_Total_Supply
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 509, 1186 ] }
3,343
BondingShareV2
contracts/UbiquityAlgorithmicDollar.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
UbiquityAlgorithmicDollar
contract UbiquityAlgorithmicDollar is ERC20Ubiquity { /// @notice get associated incentive contract, 0 address if N/A mapping(address => address) public incentiveContract; event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); constructor(address _manager) ERC20Ubiquity(_manager, "Ubiquity Algorithmic Dollar", "uAD") {} // solhint-disable-line no-empty-blocks /// @param account the account to incentivize /// @param incentive the associated incentive contract /// @notice only UAD manager can set Incentive contract function setIncentiveContract(address account, address incentive) external { require( ERC20Ubiquity.manager.hasRole( ERC20Ubiquity.manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender ), "Dollar: must have admin role" ); incentiveContract[account] = incentive; emit IncentiveContractUpdate(account, incentive); } function _checkAndApplyIncentives( address sender, address recipient, uint256 amount ) internal { // incentive on sender address senderIncentive = incentiveContract[sender]; if (senderIncentive != address(0)) { IIncentive(senderIncentive).incentivize( sender, recipient, msg.sender, amount ); } // incentive on recipient address recipientIncentive = incentiveContract[recipient]; if (recipientIncentive != address(0)) { IIncentive(recipientIncentive).incentivize( sender, recipient, msg.sender, amount ); } // incentive on operator address operatorIncentive = incentiveContract[msg.sender]; if ( msg.sender != sender && msg.sender != recipient && operatorIncentive != address(0) ) { IIncentive(operatorIncentive).incentivize( sender, recipient, msg.sender, amount ); } // all incentive, if active applies to every transfer address allIncentive = incentiveContract[address(0)]; if (allIncentive != address(0)) { IIncentive(allIncentive).incentivize( sender, recipient, msg.sender, amount ); } } function _transfer( address sender, address recipient, uint256 amount ) internal override { super._transfer(sender, recipient, amount); _checkAndApplyIncentives(sender, recipient, amount); } }
setIncentiveContract
function setIncentiveContract(address account, address incentive) external { require( ERC20Ubiquity.manager.hasRole( ERC20Ubiquity.manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender ), "Dollar: must have admin role" ); incentiveContract[account] = incentive; emit IncentiveContractUpdate(account, incentive); }
/// @param account the account to incentivize /// @param incentive the associated incentive contract /// @notice only UAD manager can set Incentive contract
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 627, 1040 ] }
3,344
AlphaDraconis
contracts/AlphaDraconis.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
AlphaDraconis
contract AlphaDraconis is Ownable, ERC721A, ReentrancyGuard { uint32 preSaleStartTime = 1643378400; uint32 publicSaleStartTime = 1643464800; uint256 public maxPerAddressDuringMint; uint256 public whitelistPrice = 35000000000000000; uint256 public publicPrice = 50000000000000000; uint256 MAX_MINT = 5; uint32 collectionSize = 8888; mapping(address => uint256) public freelist; mapping(address => uint256) public whitelist; string public notRevealedURI = "https://alphadraconis.mypinata.cloud/ipfs/QmURm5Bex2ZzkBADrmdKSZvRapA6zjxdodQJNnx3RvoPGp"; constructor(uint256 maxBatchSize_) ERC721A("Alpha Draconis", "ALPHADRACONIS", maxBatchSize_) { maxPerAddressDuringMint = maxBatchSize_; } // Utilities modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } function refundIfOver(uint256 price) private { require(msg.value >= price, "Need to send more ETH."); if (msg.value > price) { payable(msg.sender).transfer(msg.value - price); } } function checkPrice(uint256 _price, uint _count) public pure returns (uint256) { return _price * _count; } // Main functions function mint(uint256 quantity) external payable callerIsUser { require( totalSupply() + quantity <= collectionSize, "reached max supply" ); if (freelist[msg.sender] > 0) { require(freelist[msg.sender] > 0, "You are not in freelist"); require( block.timestamp >= preSaleStartTime, "Whitelist sale not started. " ); require(quantity <= MAX_MINT, "Exceed max quantity per mint"); require(quantity <= freelist[msg.sender], "Exceed max quantity you can mint"); // free mint uint256 price = 0; require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); _safeMint(msg.sender, quantity); refundIfOver(price); freelist[msg.sender] -= quantity; } else if (whitelist[msg.sender] > 0) { require(whitelist[msg.sender] > 0, "You are not in whitelist"); require( block.timestamp >= preSaleStartTime, "Whitelist sale not started. " ); require(quantity <= MAX_MINT, "Exceed max quantity per mint"); require(quantity <= whitelist[msg.sender], "Exceed max quantity you can mint"); // white list mint uint256 price = uint256(whitelistPrice); require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); refundIfOver(price*quantity); _safeMint(msg.sender, quantity); whitelist[msg.sender] -= quantity; } else { // public mint uint256 price = uint256(publicPrice); require( block.timestamp >= publicSaleStartTime, "Public Sale not started. " ); require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); refundIfOver(price*quantity); _safeMint(msg.sender, quantity); } } // URI // Reveal Logic bool private _isRevealed = false; // // metadata URI string private _baseTokenURI = "https://alphadraconis.mypinata.cloud/ipfs/QmaSKR8VefQfKjdGs3fGAvbAdp4X63WJvNDrmiK2tqPMv9/"; function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string calldata baseURI) external onlyOwner { _baseTokenURI = baseURI; } function revealCollection() public onlyOwner{ _isRevealed = true; } function hideCollection() public onlyOwner{ _isRevealed = false; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory){ if (_isRevealed == true){ return super.tokenURI(tokenId); } else { return notRevealedURI; } } // Address Functions function setWhitelist(address[] memory addresses, uint256[] memory numSlots) external onlyOwner { require( addresses.length == numSlots.length, "addresses does not match numSlots length" ); for (uint256 i = 0; i < addresses.length; i++) { whitelist[addresses[i]] = numSlots[i]; } } function setFreelist(address[] memory addresses, uint256[] memory numSlots) external onlyOwner { require( addresses.length == numSlots.length, "addresses does not match numSlots length" ); for (uint256 i = 0; i < addresses.length; i++) { freelist[addresses[i]] = numSlots[i]; } } // Withdraw function withdrawMoney() external onlyOwner nonReentrant { require(address(this).balance > 0, "No ether left to withdraw"); (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } // Update timestamp function changePresaleTime(uint32 _newDate) public onlyOwner { preSaleStartTime = _newDate; } function changePublicSaleTime(uint32 _newDate) public onlyOwner { publicSaleStartTime = _newDate; } function changeMaxMint(uint32 _newMax) public onlyOwner { MAX_MINT = _newMax; } function changePresalePrice(uint256 _newPrice) public onlyOwner { whitelistPrice = _newPrice; } function changePublicPrice(uint256 _newPrice) public onlyOwner { publicPrice = _newPrice; } }
mint
function mint(uint256 quantity) external payable callerIsUser { require( totalSupply() + quantity <= collectionSize, "reached max supply" ); if (freelist[msg.sender] > 0) { require(freelist[msg.sender] > 0, "You are not in freelist"); require( block.timestamp >= preSaleStartTime, "Whitelist sale not started. " ); require(quantity <= MAX_MINT, "Exceed max quantity per mint"); require(quantity <= freelist[msg.sender], "Exceed max quantity you can mint"); // free mint uint256 price = 0; require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); _safeMint(msg.sender, quantity); refundIfOver(price); freelist[msg.sender] -= quantity; } else if (whitelist[msg.sender] > 0) { require(whitelist[msg.sender] > 0, "You are not in whitelist"); require( block.timestamp >= preSaleStartTime, "Whitelist sale not started. " ); require(quantity <= MAX_MINT, "Exceed max quantity per mint"); require(quantity <= whitelist[msg.sender], "Exceed max quantity you can mint"); // white list mint uint256 price = uint256(whitelistPrice); require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); refundIfOver(price*quantity); _safeMint(msg.sender, quantity); whitelist[msg.sender] -= quantity; } else { // public mint uint256 price = uint256(publicPrice); require( block.timestamp >= publicSaleStartTime, "Public Sale not started. " ); require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); refundIfOver(price*quantity); _safeMint(msg.sender, quantity); } }
// Main functions
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 1308, 3498 ] }
3,345
AlphaDraconis
contracts/AlphaDraconis.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
AlphaDraconis
contract AlphaDraconis is Ownable, ERC721A, ReentrancyGuard { uint32 preSaleStartTime = 1643378400; uint32 publicSaleStartTime = 1643464800; uint256 public maxPerAddressDuringMint; uint256 public whitelistPrice = 35000000000000000; uint256 public publicPrice = 50000000000000000; uint256 MAX_MINT = 5; uint32 collectionSize = 8888; mapping(address => uint256) public freelist; mapping(address => uint256) public whitelist; string public notRevealedURI = "https://alphadraconis.mypinata.cloud/ipfs/QmURm5Bex2ZzkBADrmdKSZvRapA6zjxdodQJNnx3RvoPGp"; constructor(uint256 maxBatchSize_) ERC721A("Alpha Draconis", "ALPHADRACONIS", maxBatchSize_) { maxPerAddressDuringMint = maxBatchSize_; } // Utilities modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } function refundIfOver(uint256 price) private { require(msg.value >= price, "Need to send more ETH."); if (msg.value > price) { payable(msg.sender).transfer(msg.value - price); } } function checkPrice(uint256 _price, uint _count) public pure returns (uint256) { return _price * _count; } // Main functions function mint(uint256 quantity) external payable callerIsUser { require( totalSupply() + quantity <= collectionSize, "reached max supply" ); if (freelist[msg.sender] > 0) { require(freelist[msg.sender] > 0, "You are not in freelist"); require( block.timestamp >= preSaleStartTime, "Whitelist sale not started. " ); require(quantity <= MAX_MINT, "Exceed max quantity per mint"); require(quantity <= freelist[msg.sender], "Exceed max quantity you can mint"); // free mint uint256 price = 0; require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); _safeMint(msg.sender, quantity); refundIfOver(price); freelist[msg.sender] -= quantity; } else if (whitelist[msg.sender] > 0) { require(whitelist[msg.sender] > 0, "You are not in whitelist"); require( block.timestamp >= preSaleStartTime, "Whitelist sale not started. " ); require(quantity <= MAX_MINT, "Exceed max quantity per mint"); require(quantity <= whitelist[msg.sender], "Exceed max quantity you can mint"); // white list mint uint256 price = uint256(whitelistPrice); require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); refundIfOver(price*quantity); _safeMint(msg.sender, quantity); whitelist[msg.sender] -= quantity; } else { // public mint uint256 price = uint256(publicPrice); require( block.timestamp >= publicSaleStartTime, "Public Sale not started. " ); require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); refundIfOver(price*quantity); _safeMint(msg.sender, quantity); } } // URI // Reveal Logic bool private _isRevealed = false; // // metadata URI string private _baseTokenURI = "https://alphadraconis.mypinata.cloud/ipfs/QmaSKR8VefQfKjdGs3fGAvbAdp4X63WJvNDrmiK2tqPMv9/"; function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string calldata baseURI) external onlyOwner { _baseTokenURI = baseURI; } function revealCollection() public onlyOwner{ _isRevealed = true; } function hideCollection() public onlyOwner{ _isRevealed = false; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory){ if (_isRevealed == true){ return super.tokenURI(tokenId); } else { return notRevealedURI; } } // Address Functions function setWhitelist(address[] memory addresses, uint256[] memory numSlots) external onlyOwner { require( addresses.length == numSlots.length, "addresses does not match numSlots length" ); for (uint256 i = 0; i < addresses.length; i++) { whitelist[addresses[i]] = numSlots[i]; } } function setFreelist(address[] memory addresses, uint256[] memory numSlots) external onlyOwner { require( addresses.length == numSlots.length, "addresses does not match numSlots length" ); for (uint256 i = 0; i < addresses.length; i++) { freelist[addresses[i]] = numSlots[i]; } } // Withdraw function withdrawMoney() external onlyOwner nonReentrant { require(address(this).balance > 0, "No ether left to withdraw"); (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } // Update timestamp function changePresaleTime(uint32 _newDate) public onlyOwner { preSaleStartTime = _newDate; } function changePublicSaleTime(uint32 _newDate) public onlyOwner { publicSaleStartTime = _newDate; } function changeMaxMint(uint32 _newMax) public onlyOwner { MAX_MINT = _newMax; } function changePresalePrice(uint256 _newPrice) public onlyOwner { whitelistPrice = _newPrice; } function changePublicPrice(uint256 _newPrice) public onlyOwner { publicPrice = _newPrice; } }
setWhitelist
function setWhitelist(address[] memory addresses, uint256[] memory numSlots) external onlyOwner { require( addresses.length == numSlots.length, "addresses does not match numSlots length" ); for (uint256 i = 0; i < addresses.length; i++) { whitelist[addresses[i]] = numSlots[i]; } }
// Address Functions
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 4387, 4728 ] }
3,346
AlphaDraconis
contracts/AlphaDraconis.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
AlphaDraconis
contract AlphaDraconis is Ownable, ERC721A, ReentrancyGuard { uint32 preSaleStartTime = 1643378400; uint32 publicSaleStartTime = 1643464800; uint256 public maxPerAddressDuringMint; uint256 public whitelistPrice = 35000000000000000; uint256 public publicPrice = 50000000000000000; uint256 MAX_MINT = 5; uint32 collectionSize = 8888; mapping(address => uint256) public freelist; mapping(address => uint256) public whitelist; string public notRevealedURI = "https://alphadraconis.mypinata.cloud/ipfs/QmURm5Bex2ZzkBADrmdKSZvRapA6zjxdodQJNnx3RvoPGp"; constructor(uint256 maxBatchSize_) ERC721A("Alpha Draconis", "ALPHADRACONIS", maxBatchSize_) { maxPerAddressDuringMint = maxBatchSize_; } // Utilities modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } function refundIfOver(uint256 price) private { require(msg.value >= price, "Need to send more ETH."); if (msg.value > price) { payable(msg.sender).transfer(msg.value - price); } } function checkPrice(uint256 _price, uint _count) public pure returns (uint256) { return _price * _count; } // Main functions function mint(uint256 quantity) external payable callerIsUser { require( totalSupply() + quantity <= collectionSize, "reached max supply" ); if (freelist[msg.sender] > 0) { require(freelist[msg.sender] > 0, "You are not in freelist"); require( block.timestamp >= preSaleStartTime, "Whitelist sale not started. " ); require(quantity <= MAX_MINT, "Exceed max quantity per mint"); require(quantity <= freelist[msg.sender], "Exceed max quantity you can mint"); // free mint uint256 price = 0; require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); _safeMint(msg.sender, quantity); refundIfOver(price); freelist[msg.sender] -= quantity; } else if (whitelist[msg.sender] > 0) { require(whitelist[msg.sender] > 0, "You are not in whitelist"); require( block.timestamp >= preSaleStartTime, "Whitelist sale not started. " ); require(quantity <= MAX_MINT, "Exceed max quantity per mint"); require(quantity <= whitelist[msg.sender], "Exceed max quantity you can mint"); // white list mint uint256 price = uint256(whitelistPrice); require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); refundIfOver(price*quantity); _safeMint(msg.sender, quantity); whitelist[msg.sender] -= quantity; } else { // public mint uint256 price = uint256(publicPrice); require( block.timestamp >= publicSaleStartTime, "Public Sale not started. " ); require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); refundIfOver(price*quantity); _safeMint(msg.sender, quantity); } } // URI // Reveal Logic bool private _isRevealed = false; // // metadata URI string private _baseTokenURI = "https://alphadraconis.mypinata.cloud/ipfs/QmaSKR8VefQfKjdGs3fGAvbAdp4X63WJvNDrmiK2tqPMv9/"; function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string calldata baseURI) external onlyOwner { _baseTokenURI = baseURI; } function revealCollection() public onlyOwner{ _isRevealed = true; } function hideCollection() public onlyOwner{ _isRevealed = false; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory){ if (_isRevealed == true){ return super.tokenURI(tokenId); } else { return notRevealedURI; } } // Address Functions function setWhitelist(address[] memory addresses, uint256[] memory numSlots) external onlyOwner { require( addresses.length == numSlots.length, "addresses does not match numSlots length" ); for (uint256 i = 0; i < addresses.length; i++) { whitelist[addresses[i]] = numSlots[i]; } } function setFreelist(address[] memory addresses, uint256[] memory numSlots) external onlyOwner { require( addresses.length == numSlots.length, "addresses does not match numSlots length" ); for (uint256 i = 0; i < addresses.length; i++) { freelist[addresses[i]] = numSlots[i]; } } // Withdraw function withdrawMoney() external onlyOwner nonReentrant { require(address(this).balance > 0, "No ether left to withdraw"); (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } // Update timestamp function changePresaleTime(uint32 _newDate) public onlyOwner { preSaleStartTime = _newDate; } function changePublicSaleTime(uint32 _newDate) public onlyOwner { publicSaleStartTime = _newDate; } function changeMaxMint(uint32 _newMax) public onlyOwner { MAX_MINT = _newMax; } function changePresalePrice(uint256 _newPrice) public onlyOwner { whitelistPrice = _newPrice; } function changePublicPrice(uint256 _newPrice) public onlyOwner { publicPrice = _newPrice; } }
withdrawMoney
function withdrawMoney() external onlyOwner nonReentrant { require(address(this).balance > 0, "No ether left to withdraw"); (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); }
// Withdraw
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 5090, 5344 ] }
3,347
AlphaDraconis
contracts/AlphaDraconis.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
AlphaDraconis
contract AlphaDraconis is Ownable, ERC721A, ReentrancyGuard { uint32 preSaleStartTime = 1643378400; uint32 publicSaleStartTime = 1643464800; uint256 public maxPerAddressDuringMint; uint256 public whitelistPrice = 35000000000000000; uint256 public publicPrice = 50000000000000000; uint256 MAX_MINT = 5; uint32 collectionSize = 8888; mapping(address => uint256) public freelist; mapping(address => uint256) public whitelist; string public notRevealedURI = "https://alphadraconis.mypinata.cloud/ipfs/QmURm5Bex2ZzkBADrmdKSZvRapA6zjxdodQJNnx3RvoPGp"; constructor(uint256 maxBatchSize_) ERC721A("Alpha Draconis", "ALPHADRACONIS", maxBatchSize_) { maxPerAddressDuringMint = maxBatchSize_; } // Utilities modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } function refundIfOver(uint256 price) private { require(msg.value >= price, "Need to send more ETH."); if (msg.value > price) { payable(msg.sender).transfer(msg.value - price); } } function checkPrice(uint256 _price, uint _count) public pure returns (uint256) { return _price * _count; } // Main functions function mint(uint256 quantity) external payable callerIsUser { require( totalSupply() + quantity <= collectionSize, "reached max supply" ); if (freelist[msg.sender] > 0) { require(freelist[msg.sender] > 0, "You are not in freelist"); require( block.timestamp >= preSaleStartTime, "Whitelist sale not started. " ); require(quantity <= MAX_MINT, "Exceed max quantity per mint"); require(quantity <= freelist[msg.sender], "Exceed max quantity you can mint"); // free mint uint256 price = 0; require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); _safeMint(msg.sender, quantity); refundIfOver(price); freelist[msg.sender] -= quantity; } else if (whitelist[msg.sender] > 0) { require(whitelist[msg.sender] > 0, "You are not in whitelist"); require( block.timestamp >= preSaleStartTime, "Whitelist sale not started. " ); require(quantity <= MAX_MINT, "Exceed max quantity per mint"); require(quantity <= whitelist[msg.sender], "Exceed max quantity you can mint"); // white list mint uint256 price = uint256(whitelistPrice); require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); refundIfOver(price*quantity); _safeMint(msg.sender, quantity); whitelist[msg.sender] -= quantity; } else { // public mint uint256 price = uint256(publicPrice); require( block.timestamp >= publicSaleStartTime, "Public Sale not started. " ); require(msg.value >= checkPrice(price, quantity), "Value below price, need to pay more"); refundIfOver(price*quantity); _safeMint(msg.sender, quantity); } } // URI // Reveal Logic bool private _isRevealed = false; // // metadata URI string private _baseTokenURI = "https://alphadraconis.mypinata.cloud/ipfs/QmaSKR8VefQfKjdGs3fGAvbAdp4X63WJvNDrmiK2tqPMv9/"; function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string calldata baseURI) external onlyOwner { _baseTokenURI = baseURI; } function revealCollection() public onlyOwner{ _isRevealed = true; } function hideCollection() public onlyOwner{ _isRevealed = false; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory){ if (_isRevealed == true){ return super.tokenURI(tokenId); } else { return notRevealedURI; } } // Address Functions function setWhitelist(address[] memory addresses, uint256[] memory numSlots) external onlyOwner { require( addresses.length == numSlots.length, "addresses does not match numSlots length" ); for (uint256 i = 0; i < addresses.length; i++) { whitelist[addresses[i]] = numSlots[i]; } } function setFreelist(address[] memory addresses, uint256[] memory numSlots) external onlyOwner { require( addresses.length == numSlots.length, "addresses does not match numSlots length" ); for (uint256 i = 0; i < addresses.length; i++) { freelist[addresses[i]] = numSlots[i]; } } // Withdraw function withdrawMoney() external onlyOwner nonReentrant { require(address(this).balance > 0, "No ether left to withdraw"); (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } // Update timestamp function changePresaleTime(uint32 _newDate) public onlyOwner { preSaleStartTime = _newDate; } function changePublicSaleTime(uint32 _newDate) public onlyOwner { publicSaleStartTime = _newDate; } function changeMaxMint(uint32 _newMax) public onlyOwner { MAX_MINT = _newMax; } function changePresalePrice(uint256 _newPrice) public onlyOwner { whitelistPrice = _newPrice; } function changePublicPrice(uint256 _newPrice) public onlyOwner { publicPrice = _newPrice; } }
changePresaleTime
function changePresaleTime(uint32 _newDate) public onlyOwner { preSaleStartTime = _newDate;
// Update timestamp
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 5370, 5484 ] }
3,348
BondingShareV2
contracts/ExcessDollarsDistributor.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ExcessDollarsDistributor
contract ExcessDollarsDistributor is IExcessDollarsDistributor { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; UbiquityAlgorithmicDollarManager public manager; uint256 private immutable _minAmountToDistribute = 100 ether; IUniswapV2Router02 private immutable _router = IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // SushiV2Router02 /// @param _manager the address of the manager contract so we can fetch variables constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } function distributeDollars() external override { //the excess dollars which were sent to this contract by the coupon manager uint256 excessDollars = IERC20Ubiquity(manager.dollarTokenAddress()) .balanceOf(address(this)); if (excessDollars > _minAmountToDistribute) { address treasuryAddress = manager.treasuryAddress(); // curve uAD-3CRV liquidity pool uint256 tenPercent = excessDollars .fromUInt() .div(uint256(10).fromUInt()) .toUInt(); uint256 fiftyPercent = excessDollars .fromUInt() .div(uint256(2).fromUInt()) .toUInt(); IERC20Ubiquity(manager.dollarTokenAddress()).safeTransfer( treasuryAddress, fiftyPercent ); // convert uAD to uGOV-UAD LP on sushi and burn them _governanceBuyBackLPAndBurn(tenPercent); // convert remaining uAD to curve LP tokens // and transfer the curve LP tokens to the bonding contract _convertToCurveLPAndTransfer( excessDollars - fiftyPercent - tenPercent ); } } // swap half amount to uGOV function _swapDollarsForGovernance(bytes16 amountIn) internal returns (uint256) { address[] memory path = new address[](2); path[0] = manager.dollarTokenAddress(); path[1] = manager.governanceTokenAddress(); uint256[] memory amounts = _router.swapExactTokensForTokens( amountIn.toUInt(), 0, path, address(this), block.timestamp + 100 ); return amounts[1]; } // buy-back and burn uGOV function _governanceBuyBackLPAndBurn(uint256 amount) internal { bytes16 amountUAD = (amount.fromUInt()).div(uint256(2).fromUInt()); // we need to approve sushi router IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( address(_router), 0 ); IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( address(_router), amount ); uint256 amountUGOV = _swapDollarsForGovernance(amountUAD); IERC20Ubiquity(manager.governanceTokenAddress()).safeApprove( address(_router), 0 ); IERC20Ubiquity(manager.governanceTokenAddress()).safeApprove( address(_router), amountUGOV ); // deposit liquidity and transfer to zero address (burn) _router.addLiquidity( manager.dollarTokenAddress(), manager.governanceTokenAddress(), amountUAD.toUInt(), amountUGOV, 0, 0, address(0), block.timestamp + 100 ); } // @dev convert to curve LP // @param amount to convert to curve LP by swapping to 3CRV // and deposit the 3CRV as liquidity to get uAD-3CRV LP tokens // the LP token are sent to the bonding contract function _convertToCurveLPAndTransfer(uint256 amount) internal returns (uint256) { // we need to approve metaPool IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), 0 ); IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), amount ); // swap amount of uAD => 3CRV uint256 amount3CRVReceived = IMetaPool( manager.stableSwapMetaPoolAddress() ).exchange(0, 1, amount, 0); // approve metapool to transfer our 3CRV IERC20(manager.curve3PoolTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), 0 ); IERC20(manager.curve3PoolTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), amount3CRVReceived ); // deposit liquidity uint256 res = IMetaPool(manager.stableSwapMetaPoolAddress()) .add_liquidity( [0, amount3CRVReceived], 0, manager.bondingContractAddress() ); // update TWAP price return res; } }
/// @title An excess dollar distributor which sends dollars to treasury, /// lp rewards and inflation rewards
NatSpecSingleLine
_swapDollarsForGovernance
function _swapDollarsForGovernance(bytes16 amountIn) internal returns (uint256) { address[] memory path = new address[](2); path[0] = manager.dollarTokenAddress(); path[1] = manager.governanceTokenAddress(); uint256[] memory amounts = _router.swapExactTokensForTokens( amountIn.toUInt(), 0, path, address(this), block.timestamp + 100 ); return amounts[1]; }
// swap half amount to uGOV
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1933, 2427 ] }
3,349
BondingShareV2
contracts/ExcessDollarsDistributor.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ExcessDollarsDistributor
contract ExcessDollarsDistributor is IExcessDollarsDistributor { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; UbiquityAlgorithmicDollarManager public manager; uint256 private immutable _minAmountToDistribute = 100 ether; IUniswapV2Router02 private immutable _router = IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // SushiV2Router02 /// @param _manager the address of the manager contract so we can fetch variables constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } function distributeDollars() external override { //the excess dollars which were sent to this contract by the coupon manager uint256 excessDollars = IERC20Ubiquity(manager.dollarTokenAddress()) .balanceOf(address(this)); if (excessDollars > _minAmountToDistribute) { address treasuryAddress = manager.treasuryAddress(); // curve uAD-3CRV liquidity pool uint256 tenPercent = excessDollars .fromUInt() .div(uint256(10).fromUInt()) .toUInt(); uint256 fiftyPercent = excessDollars .fromUInt() .div(uint256(2).fromUInt()) .toUInt(); IERC20Ubiquity(manager.dollarTokenAddress()).safeTransfer( treasuryAddress, fiftyPercent ); // convert uAD to uGOV-UAD LP on sushi and burn them _governanceBuyBackLPAndBurn(tenPercent); // convert remaining uAD to curve LP tokens // and transfer the curve LP tokens to the bonding contract _convertToCurveLPAndTransfer( excessDollars - fiftyPercent - tenPercent ); } } // swap half amount to uGOV function _swapDollarsForGovernance(bytes16 amountIn) internal returns (uint256) { address[] memory path = new address[](2); path[0] = manager.dollarTokenAddress(); path[1] = manager.governanceTokenAddress(); uint256[] memory amounts = _router.swapExactTokensForTokens( amountIn.toUInt(), 0, path, address(this), block.timestamp + 100 ); return amounts[1]; } // buy-back and burn uGOV function _governanceBuyBackLPAndBurn(uint256 amount) internal { bytes16 amountUAD = (amount.fromUInt()).div(uint256(2).fromUInt()); // we need to approve sushi router IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( address(_router), 0 ); IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( address(_router), amount ); uint256 amountUGOV = _swapDollarsForGovernance(amountUAD); IERC20Ubiquity(manager.governanceTokenAddress()).safeApprove( address(_router), 0 ); IERC20Ubiquity(manager.governanceTokenAddress()).safeApprove( address(_router), amountUGOV ); // deposit liquidity and transfer to zero address (burn) _router.addLiquidity( manager.dollarTokenAddress(), manager.governanceTokenAddress(), amountUAD.toUInt(), amountUGOV, 0, 0, address(0), block.timestamp + 100 ); } // @dev convert to curve LP // @param amount to convert to curve LP by swapping to 3CRV // and deposit the 3CRV as liquidity to get uAD-3CRV LP tokens // the LP token are sent to the bonding contract function _convertToCurveLPAndTransfer(uint256 amount) internal returns (uint256) { // we need to approve metaPool IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), 0 ); IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), amount ); // swap amount of uAD => 3CRV uint256 amount3CRVReceived = IMetaPool( manager.stableSwapMetaPoolAddress() ).exchange(0, 1, amount, 0); // approve metapool to transfer our 3CRV IERC20(manager.curve3PoolTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), 0 ); IERC20(manager.curve3PoolTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), amount3CRVReceived ); // deposit liquidity uint256 res = IMetaPool(manager.stableSwapMetaPoolAddress()) .add_liquidity( [0, amount3CRVReceived], 0, manager.bondingContractAddress() ); // update TWAP price return res; } }
/// @title An excess dollar distributor which sends dollars to treasury, /// lp rewards and inflation rewards
NatSpecSingleLine
_governanceBuyBackLPAndBurn
function _governanceBuyBackLPAndBurn(uint256 amount) internal { bytes16 amountUAD = (amount.fromUInt()).div(uint256(2).fromUInt()); // we need to approve sushi router IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( address(_router), 0 ); IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( address(_router), amount ); uint256 amountUGOV = _swapDollarsForGovernance(amountUAD); IERC20Ubiquity(manager.governanceTokenAddress()).safeApprove( address(_router), 0 ); IERC20Ubiquity(manager.governanceTokenAddress()).safeApprove( address(_router), amountUGOV ); // deposit liquidity and transfer to zero address (burn) _router.addLiquidity( manager.dollarTokenAddress(), manager.governanceTokenAddress(), amountUAD.toUInt(), amountUGOV, 0, 0, address(0), block.timestamp + 100 ); }
// buy-back and burn uGOV
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 2459, 3565 ] }
3,350
BondingShareV2
contracts/ExcessDollarsDistributor.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
ExcessDollarsDistributor
contract ExcessDollarsDistributor is IExcessDollarsDistributor { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; UbiquityAlgorithmicDollarManager public manager; uint256 private immutable _minAmountToDistribute = 100 ether; IUniswapV2Router02 private immutable _router = IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // SushiV2Router02 /// @param _manager the address of the manager contract so we can fetch variables constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } function distributeDollars() external override { //the excess dollars which were sent to this contract by the coupon manager uint256 excessDollars = IERC20Ubiquity(manager.dollarTokenAddress()) .balanceOf(address(this)); if (excessDollars > _minAmountToDistribute) { address treasuryAddress = manager.treasuryAddress(); // curve uAD-3CRV liquidity pool uint256 tenPercent = excessDollars .fromUInt() .div(uint256(10).fromUInt()) .toUInt(); uint256 fiftyPercent = excessDollars .fromUInt() .div(uint256(2).fromUInt()) .toUInt(); IERC20Ubiquity(manager.dollarTokenAddress()).safeTransfer( treasuryAddress, fiftyPercent ); // convert uAD to uGOV-UAD LP on sushi and burn them _governanceBuyBackLPAndBurn(tenPercent); // convert remaining uAD to curve LP tokens // and transfer the curve LP tokens to the bonding contract _convertToCurveLPAndTransfer( excessDollars - fiftyPercent - tenPercent ); } } // swap half amount to uGOV function _swapDollarsForGovernance(bytes16 amountIn) internal returns (uint256) { address[] memory path = new address[](2); path[0] = manager.dollarTokenAddress(); path[1] = manager.governanceTokenAddress(); uint256[] memory amounts = _router.swapExactTokensForTokens( amountIn.toUInt(), 0, path, address(this), block.timestamp + 100 ); return amounts[1]; } // buy-back and burn uGOV function _governanceBuyBackLPAndBurn(uint256 amount) internal { bytes16 amountUAD = (amount.fromUInt()).div(uint256(2).fromUInt()); // we need to approve sushi router IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( address(_router), 0 ); IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( address(_router), amount ); uint256 amountUGOV = _swapDollarsForGovernance(amountUAD); IERC20Ubiquity(manager.governanceTokenAddress()).safeApprove( address(_router), 0 ); IERC20Ubiquity(manager.governanceTokenAddress()).safeApprove( address(_router), amountUGOV ); // deposit liquidity and transfer to zero address (burn) _router.addLiquidity( manager.dollarTokenAddress(), manager.governanceTokenAddress(), amountUAD.toUInt(), amountUGOV, 0, 0, address(0), block.timestamp + 100 ); } // @dev convert to curve LP // @param amount to convert to curve LP by swapping to 3CRV // and deposit the 3CRV as liquidity to get uAD-3CRV LP tokens // the LP token are sent to the bonding contract function _convertToCurveLPAndTransfer(uint256 amount) internal returns (uint256) { // we need to approve metaPool IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), 0 ); IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), amount ); // swap amount of uAD => 3CRV uint256 amount3CRVReceived = IMetaPool( manager.stableSwapMetaPoolAddress() ).exchange(0, 1, amount, 0); // approve metapool to transfer our 3CRV IERC20(manager.curve3PoolTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), 0 ); IERC20(manager.curve3PoolTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), amount3CRVReceived ); // deposit liquidity uint256 res = IMetaPool(manager.stableSwapMetaPoolAddress()) .add_liquidity( [0, amount3CRVReceived], 0, manager.bondingContractAddress() ); // update TWAP price return res; } }
/// @title An excess dollar distributor which sends dollars to treasury, /// lp rewards and inflation rewards
NatSpecSingleLine
_convertToCurveLPAndTransfer
function _convertToCurveLPAndTransfer(uint256 amount) internal returns (uint256) { // we need to approve metaPool IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), 0 ); IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), amount ); // swap amount of uAD => 3CRV uint256 amount3CRVReceived = IMetaPool( manager.stableSwapMetaPoolAddress() ).exchange(0, 1, amount, 0); // approve metapool to transfer our 3CRV IERC20(manager.curve3PoolTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), 0 ); IERC20(manager.curve3PoolTokenAddress()).safeApprove( manager.stableSwapMetaPoolAddress(), amount3CRVReceived ); // deposit liquidity uint256 res = IMetaPool(manager.stableSwapMetaPoolAddress()) .add_liquidity( [0, amount3CRVReceived], 0, manager.bondingContractAddress() ); // update TWAP price return res; }
// @dev convert to curve LP // @param amount to convert to curve LP by swapping to 3CRV // and deposit the 3CRV as liquidity to get uAD-3CRV LP tokens // the LP token are sent to the bonding contract
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3797, 5046 ] }
3,351
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
listExists
function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } }
/** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 464, 818 ] }
3,352
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
nodeExists
function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } }
/** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1024, 1400 ] }
3,353
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
sizeOf
function sizeOf(List storage self) internal view returns (uint256) { return self.size; }
/** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1548, 1652 ] }
3,354
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
getNode
function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } }
/** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1918, 2205 ] }
3,355
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
getAdjacent
function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } }
/** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 2531, 2807 ] }
3,356
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
getNextNode
function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); }
/** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3073, 3225 ] }
3,357
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
getPreviousNode
function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); }
/** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3495, 3651 ] }
3,358
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
getSortedSpot
function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; }
/** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 4126, 4563 ] }
3,359
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
insertAfter
function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); }
/** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 4841, 4995 ] }
3,360
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
insertBefore
function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); }
/** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 5273, 5428 ] }
3,361
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
remove
function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; }
/** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 5637, 6090 ] }
3,362
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
pushFront
function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); }
/** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 6322, 6452 ] }
3,363
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
pushBack
function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); }
/** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 6684, 6813 ] }
3,364
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
popFront
function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); }
/** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 6989, 7098 ] }
3,365
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
popBack
function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); }
/** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 7274, 7382 ] }
3,366
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
_push
function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); }
/** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 7680, 7836 ] }
3,367
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
_pop
function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); }
/** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 8071, 8269 ] }
3,368
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
_insert
function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; }
/** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 8605, 9096 ] }
3,369
BondingShareV2
solidity-linked-list/contracts/StructuredLinkedList.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
StructuredLinkedList
library StructuredLinkedList { uint256 private constant _NULL = 0; uint256 private constant _HEAD = 0; bool private constant _PREV = false; bool private constant _NEXT = true; struct List { uint256 size; mapping(uint256 => mapping(bool => uint256)) list; } /** * @dev Checks if the list exists * @param self stored linked list from contract * @return bool true if list exists, false otherwise */ function listExists(List storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[_HEAD][_PREV] != _HEAD || self.list[_HEAD][_NEXT] != _HEAD) { return true; } else { return false; } } /** * @dev Checks if the node exists * @param self stored linked list from contract * @param _node a node to search for * @return bool true if node exists, false otherwise */ function nodeExists(List storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][_PREV] == _HEAD && self.list[_node][_NEXT] == _HEAD) { if (self.list[_HEAD][_NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract * @return uint256 */ function sizeOf(List storage self) internal view returns (uint256) { return self.size; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get * @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node */ function getNode(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][_PREV], self.list[_node][_NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in * @return bool, uint256 true if node exists or false otherwise, node in _direction */ function getAdjacent(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /** * @dev Returns the link of a node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, next node */ function getNextNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _NEXT); } /** * @dev Returns the link of a node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node id of the node to step from * @return bool, uint256 true if node exists or false otherwise, previous node */ function getPreviousNode(List storage self, uint256 _node) internal view returns (bool, uint256) { return getAdjacent(self, _node, _PREV); } /** * @dev Can be used before `insert` to build an ordered list. * @dev Get the node and then `insertBefore` or `insertAfter` basing on your list order. * @dev If you want to order basing on other than `structure.getValue()` override this function * @param self stored linked list from contract * @param _structure the structure instance * @param _value value to seek * @return uint256 next node with a value less than _value */ function getSortedSpot(List storage self, address _structure, uint256 _value) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } uint256 next; (, next) = getAdjacent(self, _HEAD, _NEXT); while ((next != 0) && ((_value < IStructureInterface(_structure).getValue(next)) != _NEXT)) { next = self.list[next][_NEXT]; } return next; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_NEXT`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertAfter(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _NEXT); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_PREV`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @return bool true if success, false otherwise */ function insertBefore(List storage self, uint256 _node, uint256 _new) internal returns (bool) { return _insert(self, _node, _new, _PREV); } /** * @dev Removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list * @return uint256 the removed node */ function remove(List storage self, uint256 _node) internal returns (uint256) { if ((_node == _NULL) || (!nodeExists(self, _node))) { return 0; } _createLink(self, self.list[_node][_PREV], self.list[_node][_NEXT], _NEXT); delete self.list[_node][_PREV]; delete self.list[_node][_NEXT]; self.size -= 1; // NOT: SafeMath library should be used here to decrement. return _node; } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @return bool true if success, false otherwise */ function pushFront(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _NEXT); } /** * @dev Pushes an entry to the tail of the linked list * @param self stored linked list from contract * @param _node new entry to push to the tail * @return bool true if success, false otherwise */ function pushBack(List storage self, uint256 _node) internal returns (bool) { return _push(self, _node, _PREV); } /** * @dev Pops the first entry from the head of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popFront(List storage self) internal returns (uint256) { return _pop(self, _NEXT); } /** * @dev Pops the first entry from the tail of the linked list * @param self stored linked list from contract * @return uint256 the removed node */ function popBack(List storage self) internal returns (uint256) { return _pop(self, _PREV); } /** * @dev Pushes an entry to the head of the linked list * @param self stored linked list from contract * @param _node new entry to push to the head * @param _direction push to the head (_NEXT) or tail (_PREV) * @return bool true if success, false otherwise */ function _push(List storage self, uint256 _node, bool _direction) private returns (bool) { return _insert(self, _HEAD, _node, _direction); } /** * @dev Pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (_NEXT) or the tail (_PREV) * @return uint256 the removed node */ function _pop(List storage self, bool _direction) private returns (uint256) { uint256 adj; (, adj) = getAdjacent(self, _HEAD, _direction); return remove(self, adj); } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in * @return bool true if success, false otherwise */ function _insert(List storage self, uint256 _node, uint256 _new, bool _direction) private returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; _createLink(self, _node, _new, _direction); _createLink(self, _new, c, _direction); self.size += 1; // NOT: SafeMath library should be used here to increment. return true; } return false; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */ function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } }
/** * @title StructuredLinkedList * @author Vittorio Minacori (https://github.com/vittominacori) * @dev An utility library for using sorted linked list data structures in your Solidity project. */
NatSpecMultiLine
_createLink
function _createLink(List storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; }
/** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node existing node * @param _link node to link to in the _direction * @param _direction direction to insert node in */
NatSpecMultiLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 9392, 9591 ] }
3,370
AaveMonitorV2
contracts/mcd/saver/MCDSaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
MCDSaverProxy
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for MCD CDPs
NatSpecSingleLine
repay
function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); }
/// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 1273, 2330 ] }
3,371
AaveMonitorV2
contracts/mcd/saver/MCDSaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
MCDSaverProxy
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for MCD CDPs
NatSpecSingleLine
boost
function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); }
/// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 2476, 3562 ] }
3,372
AaveMonitorV2
contracts/mcd/saver/MCDSaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
MCDSaverProxy
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for MCD CDPs
NatSpecSingleLine
drawDai
function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; }
/// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 3848, 4651 ] }
3,373
AaveMonitorV2
contracts/mcd/saver/MCDSaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
MCDSaverProxy
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for MCD CDPs
NatSpecSingleLine
addCollateral
function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); }
/// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 4915, 5671 ] }
3,374
AaveMonitorV2
contracts/mcd/saver/MCDSaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
MCDSaverProxy
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for MCD CDPs
NatSpecSingleLine
drawCollateral
function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; }
/// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 6020, 6655 ] }
3,375
AaveMonitorV2
contracts/mcd/saver/MCDSaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
MCDSaverProxy
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for MCD CDPs
NatSpecSingleLine
paybackDebt
function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); }
/// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 7018, 7725 ] }
3,376
AaveMonitorV2
contracts/mcd/saver/MCDSaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
MCDSaverProxy
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for MCD CDPs
NatSpecSingleLine
getMaxCollateral
function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; }
/// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 8042, 8634 ] }
3,377
AaveMonitorV2
contracts/mcd/saver/MCDSaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
MCDSaverProxy
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for MCD CDPs
NatSpecSingleLine
getMaxDebt
function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); }
/// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 8896, 9250 ] }
3,378
AaveMonitorV2
contracts/mcd/saver/MCDSaverProxy.sol
0xcfd05bebb84787ee2efb2ea633981e44d754485d
Solidity
MCDSaverProxy
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } }
/// @title Implements Boost and Repay for MCD CDPs
NatSpecSingleLine
getPrice
function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); }
/// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://285ff2512c6d59b899e93c3b1f893c007ccddbbaccb0949a28275f2880f4f0ca
{ "func_code_index": [ 9329, 9538 ] }
3,379
BondingShareV2
contracts/CurveUADIncentive.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
CurveUADIncentive
contract CurveUADIncentive is IIncentive { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; UbiquityAlgorithmicDollarManager public manager; bool public isSellPenaltyOn = true; bool public isBuyIncentiveOn = true; bytes16 private immutable _one = (uint256(1 ether)).fromUInt(); mapping(address => bool) private _exempt; event ExemptAddressUpdate(address indexed _account, bool _isExempt); modifier onlyAdmin() { require( manager.hasRole(manager.INCENTIVE_MANAGER_ROLE(), msg.sender), "CurveIncentive: not admin" ); _; } modifier onlyUAD() { require( msg.sender == manager.dollarTokenAddress(), "CurveIncentive: Caller is not uAD" ); _; } /// @notice CurveIncentive constructor /// @param _manager uAD Manager constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } function incentivize( address sender, address receiver, address, uint256 amountIn ) external override onlyUAD { require(sender != receiver, "CurveIncentive: cannot send self"); if (sender == manager.stableSwapMetaPoolAddress()) { _incentivizeBuy(receiver, amountIn); } if (receiver == manager.stableSwapMetaPoolAddress()) { _incentivizeSell(sender, amountIn); } } /// @notice set an address to be exempted from Uniswap trading incentives /// @param account the address to update /// @param isExempt a flag for whether to exempt or unexempt function setExemptAddress(address account, bool isExempt) external onlyAdmin { _exempt[account] = isExempt; emit ExemptAddressUpdate(account, isExempt); } /// @notice switch the sell penalty function switchSellPenalty() external onlyAdmin { isSellPenaltyOn = !isSellPenaltyOn; } /// @notice switch the buy incentive function switchBuyIncentive() external onlyAdmin { isBuyIncentiveOn = !isBuyIncentiveOn; } /// @notice returns true if account is marked as exempt function isExemptAddress(address account) public view returns (bool) { return _exempt[account]; } function _incentivizeBuy(address target, uint256 amountIn) internal { _updateOracle(); if (isExemptAddress(target) || !isBuyIncentiveOn) { return; } uint256 incentive = _getPercentDeviationFromUnderPeg(amountIn); /* swapping 3CRV (or underlying) for uAD (aka buying uAD) will mint x% of uGOV. Where x = (1- TWAP_Price) * amountIn. E.g. uAD = 0.8, you buy 1000 uAD, you get (1-0.8)*1000 = 200 uGOV */ if (incentive != 0) { // this means CurveIncentive should be a minter of UGOV IUbiquityGovernance(manager.governanceTokenAddress()).mint( target, incentive ); } } /// @notice returns the percentage of deviation from the peg multiplied by amount // when uAD is <1$ function _getPercentDeviationFromUnderPeg(uint256 amount) internal returns (uint256) { _updateOracle(); uint256 curPrice = _getTWAPPrice(); if (curPrice >= 1 ether) { return 0; } uint256 res = _one .sub(curPrice.fromUInt()) .mul((amount.fromUInt().div(_one))) .toUInt(); // returns (1- TWAP_Price) * amount. return res; } function _incentivizeSell(address target, uint256 amount) internal { _updateOracle(); if (isExemptAddress(target) || !isSellPenaltyOn) { return; } /* WARNING From curve doc :Tokens that take a fee upon a successful transfer may cause the curve pool to break or act in unexpected ways. fei does it differently because they can make sure only one contract has the ability to sell uAD and they control the whole liquidity pool on uniswap. here to avoid problem with the curve pool we execute the transfer as specified and then we take the penalty so if penalty + amount > balance then we revert swapping uAD for 3CRV (or underlying) (aka selling uAD) will burn x% of uAD Where x = (1- TWAP_Price) *100. */ uint256 penalty = _getPercentDeviationFromUnderPeg(amount); if (penalty != 0) { require(penalty < amount, "Dollar: burn exceeds trade size"); require( UbiquityAlgorithmicDollar(manager.dollarTokenAddress()) .balanceOf(target) >= penalty + amount, "Dollar: balance too low to get penalized" ); UbiquityAlgorithmicDollar(manager.dollarTokenAddress()).burnFrom( target, penalty ); // burn from the recipient } } function _updateOracle() internal { TWAPOracle(manager.twapOracleAddress()).update(); } function _getTWAPPrice() internal view returns (uint256) { return TWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
/// @title Uniswap trading incentive contract /// @author uAD Protocol /// @dev incentives
NatSpecSingleLine
setExemptAddress
function setExemptAddress(address account, bool isExempt) external onlyAdmin { _exempt[account] = isExempt; emit ExemptAddressUpdate(account, isExempt); }
/// @notice set an address to be exempted from Uniswap trading incentives /// @param account the address to update /// @param isExempt a flag for whether to exempt or unexempt
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1645, 1843 ] }
3,380
BondingShareV2
contracts/CurveUADIncentive.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
CurveUADIncentive
contract CurveUADIncentive is IIncentive { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; UbiquityAlgorithmicDollarManager public manager; bool public isSellPenaltyOn = true; bool public isBuyIncentiveOn = true; bytes16 private immutable _one = (uint256(1 ether)).fromUInt(); mapping(address => bool) private _exempt; event ExemptAddressUpdate(address indexed _account, bool _isExempt); modifier onlyAdmin() { require( manager.hasRole(manager.INCENTIVE_MANAGER_ROLE(), msg.sender), "CurveIncentive: not admin" ); _; } modifier onlyUAD() { require( msg.sender == manager.dollarTokenAddress(), "CurveIncentive: Caller is not uAD" ); _; } /// @notice CurveIncentive constructor /// @param _manager uAD Manager constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } function incentivize( address sender, address receiver, address, uint256 amountIn ) external override onlyUAD { require(sender != receiver, "CurveIncentive: cannot send self"); if (sender == manager.stableSwapMetaPoolAddress()) { _incentivizeBuy(receiver, amountIn); } if (receiver == manager.stableSwapMetaPoolAddress()) { _incentivizeSell(sender, amountIn); } } /// @notice set an address to be exempted from Uniswap trading incentives /// @param account the address to update /// @param isExempt a flag for whether to exempt or unexempt function setExemptAddress(address account, bool isExempt) external onlyAdmin { _exempt[account] = isExempt; emit ExemptAddressUpdate(account, isExempt); } /// @notice switch the sell penalty function switchSellPenalty() external onlyAdmin { isSellPenaltyOn = !isSellPenaltyOn; } /// @notice switch the buy incentive function switchBuyIncentive() external onlyAdmin { isBuyIncentiveOn = !isBuyIncentiveOn; } /// @notice returns true if account is marked as exempt function isExemptAddress(address account) public view returns (bool) { return _exempt[account]; } function _incentivizeBuy(address target, uint256 amountIn) internal { _updateOracle(); if (isExemptAddress(target) || !isBuyIncentiveOn) { return; } uint256 incentive = _getPercentDeviationFromUnderPeg(amountIn); /* swapping 3CRV (or underlying) for uAD (aka buying uAD) will mint x% of uGOV. Where x = (1- TWAP_Price) * amountIn. E.g. uAD = 0.8, you buy 1000 uAD, you get (1-0.8)*1000 = 200 uGOV */ if (incentive != 0) { // this means CurveIncentive should be a minter of UGOV IUbiquityGovernance(manager.governanceTokenAddress()).mint( target, incentive ); } } /// @notice returns the percentage of deviation from the peg multiplied by amount // when uAD is <1$ function _getPercentDeviationFromUnderPeg(uint256 amount) internal returns (uint256) { _updateOracle(); uint256 curPrice = _getTWAPPrice(); if (curPrice >= 1 ether) { return 0; } uint256 res = _one .sub(curPrice.fromUInt()) .mul((amount.fromUInt().div(_one))) .toUInt(); // returns (1- TWAP_Price) * amount. return res; } function _incentivizeSell(address target, uint256 amount) internal { _updateOracle(); if (isExemptAddress(target) || !isSellPenaltyOn) { return; } /* WARNING From curve doc :Tokens that take a fee upon a successful transfer may cause the curve pool to break or act in unexpected ways. fei does it differently because they can make sure only one contract has the ability to sell uAD and they control the whole liquidity pool on uniswap. here to avoid problem with the curve pool we execute the transfer as specified and then we take the penalty so if penalty + amount > balance then we revert swapping uAD for 3CRV (or underlying) (aka selling uAD) will burn x% of uAD Where x = (1- TWAP_Price) *100. */ uint256 penalty = _getPercentDeviationFromUnderPeg(amount); if (penalty != 0) { require(penalty < amount, "Dollar: burn exceeds trade size"); require( UbiquityAlgorithmicDollar(manager.dollarTokenAddress()) .balanceOf(target) >= penalty + amount, "Dollar: balance too low to get penalized" ); UbiquityAlgorithmicDollar(manager.dollarTokenAddress()).burnFrom( target, penalty ); // burn from the recipient } } function _updateOracle() internal { TWAPOracle(manager.twapOracleAddress()).update(); } function _getTWAPPrice() internal view returns (uint256) { return TWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
/// @title Uniswap trading incentive contract /// @author uAD Protocol /// @dev incentives
NatSpecSingleLine
switchSellPenalty
function switchSellPenalty() external onlyAdmin { isSellPenaltyOn = !isSellPenaltyOn; }
/// @notice switch the sell penalty
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 1885, 1988 ] }
3,381
BondingShareV2
contracts/CurveUADIncentive.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
CurveUADIncentive
contract CurveUADIncentive is IIncentive { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; UbiquityAlgorithmicDollarManager public manager; bool public isSellPenaltyOn = true; bool public isBuyIncentiveOn = true; bytes16 private immutable _one = (uint256(1 ether)).fromUInt(); mapping(address => bool) private _exempt; event ExemptAddressUpdate(address indexed _account, bool _isExempt); modifier onlyAdmin() { require( manager.hasRole(manager.INCENTIVE_MANAGER_ROLE(), msg.sender), "CurveIncentive: not admin" ); _; } modifier onlyUAD() { require( msg.sender == manager.dollarTokenAddress(), "CurveIncentive: Caller is not uAD" ); _; } /// @notice CurveIncentive constructor /// @param _manager uAD Manager constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } function incentivize( address sender, address receiver, address, uint256 amountIn ) external override onlyUAD { require(sender != receiver, "CurveIncentive: cannot send self"); if (sender == manager.stableSwapMetaPoolAddress()) { _incentivizeBuy(receiver, amountIn); } if (receiver == manager.stableSwapMetaPoolAddress()) { _incentivizeSell(sender, amountIn); } } /// @notice set an address to be exempted from Uniswap trading incentives /// @param account the address to update /// @param isExempt a flag for whether to exempt or unexempt function setExemptAddress(address account, bool isExempt) external onlyAdmin { _exempt[account] = isExempt; emit ExemptAddressUpdate(account, isExempt); } /// @notice switch the sell penalty function switchSellPenalty() external onlyAdmin { isSellPenaltyOn = !isSellPenaltyOn; } /// @notice switch the buy incentive function switchBuyIncentive() external onlyAdmin { isBuyIncentiveOn = !isBuyIncentiveOn; } /// @notice returns true if account is marked as exempt function isExemptAddress(address account) public view returns (bool) { return _exempt[account]; } function _incentivizeBuy(address target, uint256 amountIn) internal { _updateOracle(); if (isExemptAddress(target) || !isBuyIncentiveOn) { return; } uint256 incentive = _getPercentDeviationFromUnderPeg(amountIn); /* swapping 3CRV (or underlying) for uAD (aka buying uAD) will mint x% of uGOV. Where x = (1- TWAP_Price) * amountIn. E.g. uAD = 0.8, you buy 1000 uAD, you get (1-0.8)*1000 = 200 uGOV */ if (incentive != 0) { // this means CurveIncentive should be a minter of UGOV IUbiquityGovernance(manager.governanceTokenAddress()).mint( target, incentive ); } } /// @notice returns the percentage of deviation from the peg multiplied by amount // when uAD is <1$ function _getPercentDeviationFromUnderPeg(uint256 amount) internal returns (uint256) { _updateOracle(); uint256 curPrice = _getTWAPPrice(); if (curPrice >= 1 ether) { return 0; } uint256 res = _one .sub(curPrice.fromUInt()) .mul((amount.fromUInt().div(_one))) .toUInt(); // returns (1- TWAP_Price) * amount. return res; } function _incentivizeSell(address target, uint256 amount) internal { _updateOracle(); if (isExemptAddress(target) || !isSellPenaltyOn) { return; } /* WARNING From curve doc :Tokens that take a fee upon a successful transfer may cause the curve pool to break or act in unexpected ways. fei does it differently because they can make sure only one contract has the ability to sell uAD and they control the whole liquidity pool on uniswap. here to avoid problem with the curve pool we execute the transfer as specified and then we take the penalty so if penalty + amount > balance then we revert swapping uAD for 3CRV (or underlying) (aka selling uAD) will burn x% of uAD Where x = (1- TWAP_Price) *100. */ uint256 penalty = _getPercentDeviationFromUnderPeg(amount); if (penalty != 0) { require(penalty < amount, "Dollar: burn exceeds trade size"); require( UbiquityAlgorithmicDollar(manager.dollarTokenAddress()) .balanceOf(target) >= penalty + amount, "Dollar: balance too low to get penalized" ); UbiquityAlgorithmicDollar(manager.dollarTokenAddress()).burnFrom( target, penalty ); // burn from the recipient } } function _updateOracle() internal { TWAPOracle(manager.twapOracleAddress()).update(); } function _getTWAPPrice() internal view returns (uint256) { return TWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
/// @title Uniswap trading incentive contract /// @author uAD Protocol /// @dev incentives
NatSpecSingleLine
switchBuyIncentive
function switchBuyIncentive() external onlyAdmin { isBuyIncentiveOn = !isBuyIncentiveOn; }
/// @notice switch the buy incentive
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 2031, 2137 ] }
3,382
BondingShareV2
contracts/CurveUADIncentive.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
CurveUADIncentive
contract CurveUADIncentive is IIncentive { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; UbiquityAlgorithmicDollarManager public manager; bool public isSellPenaltyOn = true; bool public isBuyIncentiveOn = true; bytes16 private immutable _one = (uint256(1 ether)).fromUInt(); mapping(address => bool) private _exempt; event ExemptAddressUpdate(address indexed _account, bool _isExempt); modifier onlyAdmin() { require( manager.hasRole(manager.INCENTIVE_MANAGER_ROLE(), msg.sender), "CurveIncentive: not admin" ); _; } modifier onlyUAD() { require( msg.sender == manager.dollarTokenAddress(), "CurveIncentive: Caller is not uAD" ); _; } /// @notice CurveIncentive constructor /// @param _manager uAD Manager constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } function incentivize( address sender, address receiver, address, uint256 amountIn ) external override onlyUAD { require(sender != receiver, "CurveIncentive: cannot send self"); if (sender == manager.stableSwapMetaPoolAddress()) { _incentivizeBuy(receiver, amountIn); } if (receiver == manager.stableSwapMetaPoolAddress()) { _incentivizeSell(sender, amountIn); } } /// @notice set an address to be exempted from Uniswap trading incentives /// @param account the address to update /// @param isExempt a flag for whether to exempt or unexempt function setExemptAddress(address account, bool isExempt) external onlyAdmin { _exempt[account] = isExempt; emit ExemptAddressUpdate(account, isExempt); } /// @notice switch the sell penalty function switchSellPenalty() external onlyAdmin { isSellPenaltyOn = !isSellPenaltyOn; } /// @notice switch the buy incentive function switchBuyIncentive() external onlyAdmin { isBuyIncentiveOn = !isBuyIncentiveOn; } /// @notice returns true if account is marked as exempt function isExemptAddress(address account) public view returns (bool) { return _exempt[account]; } function _incentivizeBuy(address target, uint256 amountIn) internal { _updateOracle(); if (isExemptAddress(target) || !isBuyIncentiveOn) { return; } uint256 incentive = _getPercentDeviationFromUnderPeg(amountIn); /* swapping 3CRV (or underlying) for uAD (aka buying uAD) will mint x% of uGOV. Where x = (1- TWAP_Price) * amountIn. E.g. uAD = 0.8, you buy 1000 uAD, you get (1-0.8)*1000 = 200 uGOV */ if (incentive != 0) { // this means CurveIncentive should be a minter of UGOV IUbiquityGovernance(manager.governanceTokenAddress()).mint( target, incentive ); } } /// @notice returns the percentage of deviation from the peg multiplied by amount // when uAD is <1$ function _getPercentDeviationFromUnderPeg(uint256 amount) internal returns (uint256) { _updateOracle(); uint256 curPrice = _getTWAPPrice(); if (curPrice >= 1 ether) { return 0; } uint256 res = _one .sub(curPrice.fromUInt()) .mul((amount.fromUInt().div(_one))) .toUInt(); // returns (1- TWAP_Price) * amount. return res; } function _incentivizeSell(address target, uint256 amount) internal { _updateOracle(); if (isExemptAddress(target) || !isSellPenaltyOn) { return; } /* WARNING From curve doc :Tokens that take a fee upon a successful transfer may cause the curve pool to break or act in unexpected ways. fei does it differently because they can make sure only one contract has the ability to sell uAD and they control the whole liquidity pool on uniswap. here to avoid problem with the curve pool we execute the transfer as specified and then we take the penalty so if penalty + amount > balance then we revert swapping uAD for 3CRV (or underlying) (aka selling uAD) will burn x% of uAD Where x = (1- TWAP_Price) *100. */ uint256 penalty = _getPercentDeviationFromUnderPeg(amount); if (penalty != 0) { require(penalty < amount, "Dollar: burn exceeds trade size"); require( UbiquityAlgorithmicDollar(manager.dollarTokenAddress()) .balanceOf(target) >= penalty + amount, "Dollar: balance too low to get penalized" ); UbiquityAlgorithmicDollar(manager.dollarTokenAddress()).burnFrom( target, penalty ); // burn from the recipient } } function _updateOracle() internal { TWAPOracle(manager.twapOracleAddress()).update(); } function _getTWAPPrice() internal view returns (uint256) { return TWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
/// @title Uniswap trading incentive contract /// @author uAD Protocol /// @dev incentives
NatSpecSingleLine
isExemptAddress
function isExemptAddress(address account) public view returns (bool) { return _exempt[account]; }
/// @notice returns true if account is marked as exempt
NatSpecSingleLine
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 2199, 2312 ] }
3,383
BondingShareV2
contracts/CurveUADIncentive.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
CurveUADIncentive
contract CurveUADIncentive is IIncentive { using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; UbiquityAlgorithmicDollarManager public manager; bool public isSellPenaltyOn = true; bool public isBuyIncentiveOn = true; bytes16 private immutable _one = (uint256(1 ether)).fromUInt(); mapping(address => bool) private _exempt; event ExemptAddressUpdate(address indexed _account, bool _isExempt); modifier onlyAdmin() { require( manager.hasRole(manager.INCENTIVE_MANAGER_ROLE(), msg.sender), "CurveIncentive: not admin" ); _; } modifier onlyUAD() { require( msg.sender == manager.dollarTokenAddress(), "CurveIncentive: Caller is not uAD" ); _; } /// @notice CurveIncentive constructor /// @param _manager uAD Manager constructor(address _manager) { manager = UbiquityAlgorithmicDollarManager(_manager); } function incentivize( address sender, address receiver, address, uint256 amountIn ) external override onlyUAD { require(sender != receiver, "CurveIncentive: cannot send self"); if (sender == manager.stableSwapMetaPoolAddress()) { _incentivizeBuy(receiver, amountIn); } if (receiver == manager.stableSwapMetaPoolAddress()) { _incentivizeSell(sender, amountIn); } } /// @notice set an address to be exempted from Uniswap trading incentives /// @param account the address to update /// @param isExempt a flag for whether to exempt or unexempt function setExemptAddress(address account, bool isExempt) external onlyAdmin { _exempt[account] = isExempt; emit ExemptAddressUpdate(account, isExempt); } /// @notice switch the sell penalty function switchSellPenalty() external onlyAdmin { isSellPenaltyOn = !isSellPenaltyOn; } /// @notice switch the buy incentive function switchBuyIncentive() external onlyAdmin { isBuyIncentiveOn = !isBuyIncentiveOn; } /// @notice returns true if account is marked as exempt function isExemptAddress(address account) public view returns (bool) { return _exempt[account]; } function _incentivizeBuy(address target, uint256 amountIn) internal { _updateOracle(); if (isExemptAddress(target) || !isBuyIncentiveOn) { return; } uint256 incentive = _getPercentDeviationFromUnderPeg(amountIn); /* swapping 3CRV (or underlying) for uAD (aka buying uAD) will mint x% of uGOV. Where x = (1- TWAP_Price) * amountIn. E.g. uAD = 0.8, you buy 1000 uAD, you get (1-0.8)*1000 = 200 uGOV */ if (incentive != 0) { // this means CurveIncentive should be a minter of UGOV IUbiquityGovernance(manager.governanceTokenAddress()).mint( target, incentive ); } } /// @notice returns the percentage of deviation from the peg multiplied by amount // when uAD is <1$ function _getPercentDeviationFromUnderPeg(uint256 amount) internal returns (uint256) { _updateOracle(); uint256 curPrice = _getTWAPPrice(); if (curPrice >= 1 ether) { return 0; } uint256 res = _one .sub(curPrice.fromUInt()) .mul((amount.fromUInt().div(_one))) .toUInt(); // returns (1- TWAP_Price) * amount. return res; } function _incentivizeSell(address target, uint256 amount) internal { _updateOracle(); if (isExemptAddress(target) || !isSellPenaltyOn) { return; } /* WARNING From curve doc :Tokens that take a fee upon a successful transfer may cause the curve pool to break or act in unexpected ways. fei does it differently because they can make sure only one contract has the ability to sell uAD and they control the whole liquidity pool on uniswap. here to avoid problem with the curve pool we execute the transfer as specified and then we take the penalty so if penalty + amount > balance then we revert swapping uAD for 3CRV (or underlying) (aka selling uAD) will burn x% of uAD Where x = (1- TWAP_Price) *100. */ uint256 penalty = _getPercentDeviationFromUnderPeg(amount); if (penalty != 0) { require(penalty < amount, "Dollar: burn exceeds trade size"); require( UbiquityAlgorithmicDollar(manager.dollarTokenAddress()) .balanceOf(target) >= penalty + amount, "Dollar: balance too low to get penalized" ); UbiquityAlgorithmicDollar(manager.dollarTokenAddress()).burnFrom( target, penalty ); // burn from the recipient } } function _updateOracle() internal { TWAPOracle(manager.twapOracleAddress()).update(); } function _getTWAPPrice() internal view returns (uint256) { return TWAPOracle(manager.twapOracleAddress()).consult( manager.dollarTokenAddress() ); } }
/// @title Uniswap trading incentive contract /// @author uAD Protocol /// @dev incentives
NatSpecSingleLine
_getPercentDeviationFromUnderPeg
function _getPercentDeviationFromUnderPeg(uint256 amount) internal returns (uint256) { _updateOracle(); uint256 curPrice = _getTWAPPrice(); if (curPrice >= 1 ether) { return 0; } uint256 res = _one .sub(curPrice.fromUInt()) .mul((amount.fromUInt().div(_one))) .toUInt(); // returns (1- TWAP_Price) * amount. return res; }
// when uAD is <1$
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3168, 3622 ] }
3,384
BondingShareV2
contracts/MasterChefOriginal.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefOriginal
contract MasterChefOriginal is Ownable { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of UBQs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accUbqPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accUbqPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. // How many allocation points assigned to this pool. UBQ to distribute per block. uint256 allocPoint; uint256 lastRewardBlock; // Last block number that UBQs distribution occurs. uint256 accUbqPerShare; // Accumulated UBQs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // Block number when bonus UBQ period ends. uint256 public bonusEndBlock; // UBQ tokens created per block. uint256 public ubqPerBlock; // Bonus muliplier for early ubq makers. uint256 public constant BONUS_MULTIPLIER = 10; uint256 public uGOVDivider; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when UBQ mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } constructor( UbiquityAlgorithmicDollarManager _manager, uint256 _ubqPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) { manager = UbiquityAlgorithmicDollarManager(_manager); ubqPerBlock = _ubqPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury } function setUBQPerBlock(uint256 _ubqPerBlock) external onlyTokenManager { ubqPerBlock = _ubqPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function poolLength() external view returns (uint256) { return poolInfo.length; } // View function to see pending UBQs on frontend. function pendingUBQ(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accUbqPerShare = pool.accUbqPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 ubqReward = (multiplier * (ubqPerBlock) * (pool.allocPoint)) / (totalAllocPoint); accUbqPerShare = accUbqPerShare + ((ubqReward * (1e12)) / (lpSupply)); } return ((user.amount * accUbqPerShare) / 1e12) - user.rewardDebt; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accUbqPerShare: 0 }) ); } // Update the given pool's UBQ allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ubqReward = (multiplier * ubqPerBlock * pool.allocPoint) / totalAllocPoint; // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), ubqReward / uGOVDivider ); IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), ubqReward ); pool.accUbqPerShare = pool.accUbqPerShare + ((ubqReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for UBQ allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return ((bonusEndBlock - _from) * BONUS_MULTIPLIER) + (_to - bonusEndBlock); } } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } }
// MasterChef is the master of UBQ. He can make UBQ and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once UBQ is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
setUGOVShareForTreasury
function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; }
// the bigger uGOVDivider is the less extra Ugov will be minted for the treasury
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3194, 3342 ] }
3,385
BondingShareV2
contracts/MasterChefOriginal.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefOriginal
contract MasterChefOriginal is Ownable { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of UBQs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accUbqPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accUbqPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. // How many allocation points assigned to this pool. UBQ to distribute per block. uint256 allocPoint; uint256 lastRewardBlock; // Last block number that UBQs distribution occurs. uint256 accUbqPerShare; // Accumulated UBQs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // Block number when bonus UBQ period ends. uint256 public bonusEndBlock; // UBQ tokens created per block. uint256 public ubqPerBlock; // Bonus muliplier for early ubq makers. uint256 public constant BONUS_MULTIPLIER = 10; uint256 public uGOVDivider; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when UBQ mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } constructor( UbiquityAlgorithmicDollarManager _manager, uint256 _ubqPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) { manager = UbiquityAlgorithmicDollarManager(_manager); ubqPerBlock = _ubqPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury } function setUBQPerBlock(uint256 _ubqPerBlock) external onlyTokenManager { ubqPerBlock = _ubqPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function poolLength() external view returns (uint256) { return poolInfo.length; } // View function to see pending UBQs on frontend. function pendingUBQ(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accUbqPerShare = pool.accUbqPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 ubqReward = (multiplier * (ubqPerBlock) * (pool.allocPoint)) / (totalAllocPoint); accUbqPerShare = accUbqPerShare + ((ubqReward * (1e12)) / (lpSupply)); } return ((user.amount * accUbqPerShare) / 1e12) - user.rewardDebt; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accUbqPerShare: 0 }) ); } // Update the given pool's UBQ allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ubqReward = (multiplier * ubqPerBlock * pool.allocPoint) / totalAllocPoint; // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), ubqReward / uGOVDivider ); IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), ubqReward ); pool.accUbqPerShare = pool.accUbqPerShare + ((ubqReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for UBQ allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return ((bonusEndBlock - _from) * BONUS_MULTIPLIER) + (_to - bonusEndBlock); } } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } }
// MasterChef is the master of UBQ. He can make UBQ and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once UBQ is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
pendingUBQ
function pendingUBQ(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accUbqPerShare = pool.accUbqPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 ubqReward = (multiplier * (ubqPerBlock) * (pool.allocPoint)) / (totalAllocPoint); accUbqPerShare = accUbqPerShare + ((ubqReward * (1e12)) / (lpSupply)); } return ((user.amount * accUbqPerShare) / 1e12) - user.rewardDebt; }
// View function to see pending UBQs on frontend.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 3497, 4372 ] }
3,386
BondingShareV2
contracts/MasterChefOriginal.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefOriginal
contract MasterChefOriginal is Ownable { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of UBQs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accUbqPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accUbqPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. // How many allocation points assigned to this pool. UBQ to distribute per block. uint256 allocPoint; uint256 lastRewardBlock; // Last block number that UBQs distribution occurs. uint256 accUbqPerShare; // Accumulated UBQs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // Block number when bonus UBQ period ends. uint256 public bonusEndBlock; // UBQ tokens created per block. uint256 public ubqPerBlock; // Bonus muliplier for early ubq makers. uint256 public constant BONUS_MULTIPLIER = 10; uint256 public uGOVDivider; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when UBQ mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } constructor( UbiquityAlgorithmicDollarManager _manager, uint256 _ubqPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) { manager = UbiquityAlgorithmicDollarManager(_manager); ubqPerBlock = _ubqPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury } function setUBQPerBlock(uint256 _ubqPerBlock) external onlyTokenManager { ubqPerBlock = _ubqPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function poolLength() external view returns (uint256) { return poolInfo.length; } // View function to see pending UBQs on frontend. function pendingUBQ(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accUbqPerShare = pool.accUbqPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 ubqReward = (multiplier * (ubqPerBlock) * (pool.allocPoint)) / (totalAllocPoint); accUbqPerShare = accUbqPerShare + ((ubqReward * (1e12)) / (lpSupply)); } return ((user.amount * accUbqPerShare) / 1e12) - user.rewardDebt; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accUbqPerShare: 0 }) ); } // Update the given pool's UBQ allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ubqReward = (multiplier * ubqPerBlock * pool.allocPoint) / totalAllocPoint; // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), ubqReward / uGOVDivider ); IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), ubqReward ); pool.accUbqPerShare = pool.accUbqPerShare + ((ubqReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for UBQ allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return ((bonusEndBlock - _from) * BONUS_MULTIPLIER) + (_to - bonusEndBlock); } } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } }
// MasterChef is the master of UBQ. He can make UBQ and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once UBQ is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
add
function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accUbqPerShare: 0 }) ); }
// Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 4533, 5130 ] }
3,387
BondingShareV2
contracts/MasterChefOriginal.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefOriginal
contract MasterChefOriginal is Ownable { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of UBQs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accUbqPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accUbqPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. // How many allocation points assigned to this pool. UBQ to distribute per block. uint256 allocPoint; uint256 lastRewardBlock; // Last block number that UBQs distribution occurs. uint256 accUbqPerShare; // Accumulated UBQs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // Block number when bonus UBQ period ends. uint256 public bonusEndBlock; // UBQ tokens created per block. uint256 public ubqPerBlock; // Bonus muliplier for early ubq makers. uint256 public constant BONUS_MULTIPLIER = 10; uint256 public uGOVDivider; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when UBQ mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } constructor( UbiquityAlgorithmicDollarManager _manager, uint256 _ubqPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) { manager = UbiquityAlgorithmicDollarManager(_manager); ubqPerBlock = _ubqPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury } function setUBQPerBlock(uint256 _ubqPerBlock) external onlyTokenManager { ubqPerBlock = _ubqPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function poolLength() external view returns (uint256) { return poolInfo.length; } // View function to see pending UBQs on frontend. function pendingUBQ(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accUbqPerShare = pool.accUbqPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 ubqReward = (multiplier * (ubqPerBlock) * (pool.allocPoint)) / (totalAllocPoint); accUbqPerShare = accUbqPerShare + ((ubqReward * (1e12)) / (lpSupply)); } return ((user.amount * accUbqPerShare) / 1e12) - user.rewardDebt; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accUbqPerShare: 0 }) ); } // Update the given pool's UBQ allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ubqReward = (multiplier * ubqPerBlock * pool.allocPoint) / totalAllocPoint; // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), ubqReward / uGOVDivider ); IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), ubqReward ); pool.accUbqPerShare = pool.accUbqPerShare + ((ubqReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for UBQ allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return ((bonusEndBlock - _from) * BONUS_MULTIPLIER) + (_to - bonusEndBlock); } } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } }
// MasterChef is the master of UBQ. He can make UBQ and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once UBQ is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
set
function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; }
// Update the given pool's UBQ allocation point. Can only be called by the owner.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 5218, 5580 ] }
3,388
BondingShareV2
contracts/MasterChefOriginal.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefOriginal
contract MasterChefOriginal is Ownable { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of UBQs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accUbqPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accUbqPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. // How many allocation points assigned to this pool. UBQ to distribute per block. uint256 allocPoint; uint256 lastRewardBlock; // Last block number that UBQs distribution occurs. uint256 accUbqPerShare; // Accumulated UBQs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // Block number when bonus UBQ period ends. uint256 public bonusEndBlock; // UBQ tokens created per block. uint256 public ubqPerBlock; // Bonus muliplier for early ubq makers. uint256 public constant BONUS_MULTIPLIER = 10; uint256 public uGOVDivider; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when UBQ mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } constructor( UbiquityAlgorithmicDollarManager _manager, uint256 _ubqPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) { manager = UbiquityAlgorithmicDollarManager(_manager); ubqPerBlock = _ubqPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury } function setUBQPerBlock(uint256 _ubqPerBlock) external onlyTokenManager { ubqPerBlock = _ubqPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function poolLength() external view returns (uint256) { return poolInfo.length; } // View function to see pending UBQs on frontend. function pendingUBQ(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accUbqPerShare = pool.accUbqPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 ubqReward = (multiplier * (ubqPerBlock) * (pool.allocPoint)) / (totalAllocPoint); accUbqPerShare = accUbqPerShare + ((ubqReward * (1e12)) / (lpSupply)); } return ((user.amount * accUbqPerShare) / 1e12) - user.rewardDebt; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accUbqPerShare: 0 }) ); } // Update the given pool's UBQ allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ubqReward = (multiplier * ubqPerBlock * pool.allocPoint) / totalAllocPoint; // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), ubqReward / uGOVDivider ); IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), ubqReward ); pool.accUbqPerShare = pool.accUbqPerShare + ((ubqReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for UBQ allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return ((bonusEndBlock - _from) * BONUS_MULTIPLIER) + (_to - bonusEndBlock); } } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } }
// MasterChef is the master of UBQ. He can make UBQ and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once UBQ is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
massUpdatePools
function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } }
// Update reward vairables for all pools. Be careful of gas spending!
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 5656, 5835 ] }
3,389
BondingShareV2
contracts/MasterChefOriginal.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefOriginal
contract MasterChefOriginal is Ownable { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of UBQs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accUbqPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accUbqPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. // How many allocation points assigned to this pool. UBQ to distribute per block. uint256 allocPoint; uint256 lastRewardBlock; // Last block number that UBQs distribution occurs. uint256 accUbqPerShare; // Accumulated UBQs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // Block number when bonus UBQ period ends. uint256 public bonusEndBlock; // UBQ tokens created per block. uint256 public ubqPerBlock; // Bonus muliplier for early ubq makers. uint256 public constant BONUS_MULTIPLIER = 10; uint256 public uGOVDivider; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when UBQ mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } constructor( UbiquityAlgorithmicDollarManager _manager, uint256 _ubqPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) { manager = UbiquityAlgorithmicDollarManager(_manager); ubqPerBlock = _ubqPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury } function setUBQPerBlock(uint256 _ubqPerBlock) external onlyTokenManager { ubqPerBlock = _ubqPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function poolLength() external view returns (uint256) { return poolInfo.length; } // View function to see pending UBQs on frontend. function pendingUBQ(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accUbqPerShare = pool.accUbqPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 ubqReward = (multiplier * (ubqPerBlock) * (pool.allocPoint)) / (totalAllocPoint); accUbqPerShare = accUbqPerShare + ((ubqReward * (1e12)) / (lpSupply)); } return ((user.amount * accUbqPerShare) / 1e12) - user.rewardDebt; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accUbqPerShare: 0 }) ); } // Update the given pool's UBQ allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ubqReward = (multiplier * ubqPerBlock * pool.allocPoint) / totalAllocPoint; // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), ubqReward / uGOVDivider ); IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), ubqReward ); pool.accUbqPerShare = pool.accUbqPerShare + ((ubqReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for UBQ allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return ((bonusEndBlock - _from) * BONUS_MULTIPLIER) + (_to - bonusEndBlock); } } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } }
// MasterChef is the master of UBQ. He can make UBQ and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once UBQ is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
updatePool
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ubqReward = (multiplier * ubqPerBlock * pool.allocPoint) / totalAllocPoint; // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), ubqReward / uGOVDivider ); IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), ubqReward ); pool.accUbqPerShare = pool.accUbqPerShare + ((ubqReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; }
// Update reward variables of the given pool to be up-to-date.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 5904, 6916 ] }
3,390
BondingShareV2
contracts/MasterChefOriginal.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefOriginal
contract MasterChefOriginal is Ownable { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of UBQs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accUbqPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accUbqPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. // How many allocation points assigned to this pool. UBQ to distribute per block. uint256 allocPoint; uint256 lastRewardBlock; // Last block number that UBQs distribution occurs. uint256 accUbqPerShare; // Accumulated UBQs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // Block number when bonus UBQ period ends. uint256 public bonusEndBlock; // UBQ tokens created per block. uint256 public ubqPerBlock; // Bonus muliplier for early ubq makers. uint256 public constant BONUS_MULTIPLIER = 10; uint256 public uGOVDivider; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when UBQ mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } constructor( UbiquityAlgorithmicDollarManager _manager, uint256 _ubqPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) { manager = UbiquityAlgorithmicDollarManager(_manager); ubqPerBlock = _ubqPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury } function setUBQPerBlock(uint256 _ubqPerBlock) external onlyTokenManager { ubqPerBlock = _ubqPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function poolLength() external view returns (uint256) { return poolInfo.length; } // View function to see pending UBQs on frontend. function pendingUBQ(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accUbqPerShare = pool.accUbqPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 ubqReward = (multiplier * (ubqPerBlock) * (pool.allocPoint)) / (totalAllocPoint); accUbqPerShare = accUbqPerShare + ((ubqReward * (1e12)) / (lpSupply)); } return ((user.amount * accUbqPerShare) / 1e12) - user.rewardDebt; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accUbqPerShare: 0 }) ); } // Update the given pool's UBQ allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ubqReward = (multiplier * ubqPerBlock * pool.allocPoint) / totalAllocPoint; // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), ubqReward / uGOVDivider ); IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), ubqReward ); pool.accUbqPerShare = pool.accUbqPerShare + ((ubqReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for UBQ allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return ((bonusEndBlock - _from) * BONUS_MULTIPLIER) + (_to - bonusEndBlock); } } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } }
// MasterChef is the master of UBQ. He can make UBQ and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once UBQ is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
deposit
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); }
// Deposit LP tokens to MasterChef for UBQ allocation.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 6977, 7674 ] }
3,391
BondingShareV2
contracts/MasterChefOriginal.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefOriginal
contract MasterChefOriginal is Ownable { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of UBQs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accUbqPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accUbqPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. // How many allocation points assigned to this pool. UBQ to distribute per block. uint256 allocPoint; uint256 lastRewardBlock; // Last block number that UBQs distribution occurs. uint256 accUbqPerShare; // Accumulated UBQs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // Block number when bonus UBQ period ends. uint256 public bonusEndBlock; // UBQ tokens created per block. uint256 public ubqPerBlock; // Bonus muliplier for early ubq makers. uint256 public constant BONUS_MULTIPLIER = 10; uint256 public uGOVDivider; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when UBQ mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } constructor( UbiquityAlgorithmicDollarManager _manager, uint256 _ubqPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) { manager = UbiquityAlgorithmicDollarManager(_manager); ubqPerBlock = _ubqPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury } function setUBQPerBlock(uint256 _ubqPerBlock) external onlyTokenManager { ubqPerBlock = _ubqPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function poolLength() external view returns (uint256) { return poolInfo.length; } // View function to see pending UBQs on frontend. function pendingUBQ(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accUbqPerShare = pool.accUbqPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 ubqReward = (multiplier * (ubqPerBlock) * (pool.allocPoint)) / (totalAllocPoint); accUbqPerShare = accUbqPerShare + ((ubqReward * (1e12)) / (lpSupply)); } return ((user.amount * accUbqPerShare) / 1e12) - user.rewardDebt; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accUbqPerShare: 0 }) ); } // Update the given pool's UBQ allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ubqReward = (multiplier * ubqPerBlock * pool.allocPoint) / totalAllocPoint; // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), ubqReward / uGOVDivider ); IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), ubqReward ); pool.accUbqPerShare = pool.accUbqPerShare + ((ubqReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for UBQ allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return ((bonusEndBlock - _from) * BONUS_MULTIPLIER) + (_to - bonusEndBlock); } } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } }
// MasterChef is the master of UBQ. He can make UBQ and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once UBQ is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
withdraw
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
// Withdraw LP tokens from MasterChef.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 7719, 8363 ] }
3,392
BondingShareV2
contracts/MasterChefOriginal.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefOriginal
contract MasterChefOriginal is Ownable { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of UBQs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accUbqPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accUbqPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. // How many allocation points assigned to this pool. UBQ to distribute per block. uint256 allocPoint; uint256 lastRewardBlock; // Last block number that UBQs distribution occurs. uint256 accUbqPerShare; // Accumulated UBQs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // Block number when bonus UBQ period ends. uint256 public bonusEndBlock; // UBQ tokens created per block. uint256 public ubqPerBlock; // Bonus muliplier for early ubq makers. uint256 public constant BONUS_MULTIPLIER = 10; uint256 public uGOVDivider; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when UBQ mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } constructor( UbiquityAlgorithmicDollarManager _manager, uint256 _ubqPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) { manager = UbiquityAlgorithmicDollarManager(_manager); ubqPerBlock = _ubqPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury } function setUBQPerBlock(uint256 _ubqPerBlock) external onlyTokenManager { ubqPerBlock = _ubqPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function poolLength() external view returns (uint256) { return poolInfo.length; } // View function to see pending UBQs on frontend. function pendingUBQ(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accUbqPerShare = pool.accUbqPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 ubqReward = (multiplier * (ubqPerBlock) * (pool.allocPoint)) / (totalAllocPoint); accUbqPerShare = accUbqPerShare + ((ubqReward * (1e12)) / (lpSupply)); } return ((user.amount * accUbqPerShare) / 1e12) - user.rewardDebt; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accUbqPerShare: 0 }) ); } // Update the given pool's UBQ allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ubqReward = (multiplier * ubqPerBlock * pool.allocPoint) / totalAllocPoint; // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), ubqReward / uGOVDivider ); IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), ubqReward ); pool.accUbqPerShare = pool.accUbqPerShare + ((ubqReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for UBQ allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return ((bonusEndBlock - _from) * BONUS_MULTIPLIER) + (_to - bonusEndBlock); } } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } }
// MasterChef is the master of UBQ. He can make UBQ and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once UBQ is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
emergencyWithdraw
function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; }
// Withdraw without caring about rewards. EMERGENCY ONLY.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 8427, 8780 ] }
3,393
BondingShareV2
contracts/MasterChefOriginal.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefOriginal
contract MasterChefOriginal is Ownable { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of UBQs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accUbqPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accUbqPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. // How many allocation points assigned to this pool. UBQ to distribute per block. uint256 allocPoint; uint256 lastRewardBlock; // Last block number that UBQs distribution occurs. uint256 accUbqPerShare; // Accumulated UBQs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // Block number when bonus UBQ period ends. uint256 public bonusEndBlock; // UBQ tokens created per block. uint256 public ubqPerBlock; // Bonus muliplier for early ubq makers. uint256 public constant BONUS_MULTIPLIER = 10; uint256 public uGOVDivider; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when UBQ mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } constructor( UbiquityAlgorithmicDollarManager _manager, uint256 _ubqPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) { manager = UbiquityAlgorithmicDollarManager(_manager); ubqPerBlock = _ubqPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury } function setUBQPerBlock(uint256 _ubqPerBlock) external onlyTokenManager { ubqPerBlock = _ubqPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function poolLength() external view returns (uint256) { return poolInfo.length; } // View function to see pending UBQs on frontend. function pendingUBQ(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accUbqPerShare = pool.accUbqPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 ubqReward = (multiplier * (ubqPerBlock) * (pool.allocPoint)) / (totalAllocPoint); accUbqPerShare = accUbqPerShare + ((ubqReward * (1e12)) / (lpSupply)); } return ((user.amount * accUbqPerShare) / 1e12) - user.rewardDebt; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accUbqPerShare: 0 }) ); } // Update the given pool's UBQ allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ubqReward = (multiplier * ubqPerBlock * pool.allocPoint) / totalAllocPoint; // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), ubqReward / uGOVDivider ); IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), ubqReward ); pool.accUbqPerShare = pool.accUbqPerShare + ((ubqReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for UBQ allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return ((bonusEndBlock - _from) * BONUS_MULTIPLIER) + (_to - bonusEndBlock); } } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } }
// MasterChef is the master of UBQ. He can make UBQ and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once UBQ is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
getMultiplier
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return ((bonusEndBlock - _from) * BONUS_MULTIPLIER) + (_to - bonusEndBlock); } }
// Return reward multiplier over the given _from to _to block.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 8849, 9283 ] }
3,394
BondingShareV2
contracts/MasterChefOriginal.sol
0x2da07859613c14f6f05c97efe37b9b4f212b5ef5
Solidity
MasterChefOriginal
contract MasterChefOriginal is Ownable { using SafeERC20 for IERC20Ubiquity; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of UBQs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accUbqPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accUbqPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. // How many allocation points assigned to this pool. UBQ to distribute per block. uint256 allocPoint; uint256 lastRewardBlock; // Last block number that UBQs distribution occurs. uint256 accUbqPerShare; // Accumulated UBQs per share, times 1e12. See below. } // Ubiquity Manager UbiquityAlgorithmicDollarManager public manager; // Block number when bonus UBQ period ends. uint256 public bonusEndBlock; // UBQ tokens created per block. uint256 public ubqPerBlock; // Bonus muliplier for early ubq makers. uint256 public constant BONUS_MULTIPLIER = 10; uint256 public uGOVDivider; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when UBQ mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); // ----------- Modifiers ----------- modifier onlyTokenManager() { require( manager.hasRole(manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender), "MasterChef: not UBQ manager" ); _; } constructor( UbiquityAlgorithmicDollarManager _manager, uint256 _ubqPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) { manager = UbiquityAlgorithmicDollarManager(_manager); ubqPerBlock = _ubqPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; uGOVDivider = 5; // 100 / 5 = 20% extra minted ugov for treasury } function setUBQPerBlock(uint256 _ubqPerBlock) external onlyTokenManager { ubqPerBlock = _ubqPerBlock; } // the bigger uGOVDivider is the less extra Ugov will be minted for the treasury function setUGOVShareForTreasury(uint256 _uGOVDivider) external onlyTokenManager { uGOVDivider = _uGOVDivider; } function poolLength() external view returns (uint256) { return poolInfo.length; } // View function to see pending UBQs on frontend. function pendingUBQ(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accUbqPerShare = pool.accUbqPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 ubqReward = (multiplier * (ubqPerBlock) * (pool.allocPoint)) / (totalAllocPoint); accUbqPerShare = accUbqPerShare + ((ubqReward * (1e12)) / (lpSupply)); } return ((user.amount * accUbqPerShare) / 1e12) - user.rewardDebt; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accUbqPerShare: 0 }) ); } // Update the given pool's UBQ allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ubqReward = (multiplier * ubqPerBlock * pool.allocPoint) / totalAllocPoint; // mint another x% for the treasury IERC20Ubiquity(manager.governanceTokenAddress()).mint( manager.treasuryAddress(), ubqReward / uGOVDivider ); IERC20Ubiquity(manager.governanceTokenAddress()).mint( address(this), ubqReward ); pool.accUbqPerShare = pool.accUbqPerShare + ((ubqReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for UBQ allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount + _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accUbqPerShare) / 1e12) - user.rewardDebt; _safeUGOVTransfer(msg.sender, pending); user.amount = user.amount - _amount; user.rewardDebt = (user.amount * pool.accUbqPerShare) / 1e12; pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return ((bonusEndBlock - _from) * BONUS_MULTIPLIER) + (_to - bonusEndBlock); } } // Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs. function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } } }
// MasterChef is the master of UBQ. He can make UBQ and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once UBQ is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless.
LineComment
_safeUGOVTransfer
function _safeUGOVTransfer(address _to, uint256 _amount) internal { IERC20Ubiquity uGOV = IERC20Ubiquity(manager.governanceTokenAddress()); uint256 uGOVBal = uGOV.balanceOf(address(this)); if (_amount > uGOVBal) { uGOV.safeTransfer(_to, uGOVBal); } else { uGOV.safeTransfer(_to, _amount); } }
// Safe uGOV transfer function, just in case if rounding // error causes pool to not have enough uGOVs.
LineComment
v0.8.3+commit.8d00100c
MIT
none
{ "func_code_index": [ 9397, 9761 ] }
3,395
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
totalSupply
function totalSupply() public view override returns (uint256) { return currentIndex; }
/** * @dev See {IERC721Enumerable-totalSupply}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 1486, 1583 ] }
3,396
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
tokenByIndex
function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; }
/** * @dev See {IERC721Enumerable-tokenByIndex}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 1649, 1829 ] }
3,397
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
tokenOfOwnerByIndex
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); }
/** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 2114, 2861 ] }
3,398
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); }
/** * @dev See {IERC165-supportsInterface}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 2922, 3295 ] }
3,399
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
balanceOf
function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); }
/** * @dev See {IERC721-balanceOf}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 3348, 3562 ] }
3,400
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
ownerOf
function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; }
/** * @dev See {IERC721-ownerOf}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 4471, 4592 ] }
3,401
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
name
function name() public view virtual override returns (string memory) { return _name; }
/** * @dev See {IERC721Metadata-name}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 4648, 4745 ] }
3,402
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
symbol
function symbol() public view virtual override returns (string memory) { return _symbol; }
/** * @dev See {IERC721Metadata-symbol}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 4803, 4904 ] }
3,403
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
tokenURI
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; }
/** * @dev See {IERC721Metadata-tokenURI}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 4964, 5361 ] }
3,404
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
_baseURI
function _baseURI() internal view virtual returns (string memory) { return ""; }
/** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 5594, 5685 ] }
3,405
AlphaDraconis
contracts/ERC721A.sol
0x749b2c1ef5db3f63e4fbb64888aec78620c7eac6
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */
NatSpecMultiLine
approve
function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); }
/** * @dev See {IERC721-approve}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://b0129ac96174f95a991d497101ac24ab5f5670aaeac412cfa655370e3bcd815f
{ "func_code_index": [ 5736, 6118 ] }
3,406