Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
5
// What if balance is low?
function deathProcessing(address _enemyAddr, uint enemyPubkey, int32 damage) internal override { tvm.accept(); for ((address unitAddr, ) : UnitsMap) { IWarGameUnit(unitAddr).deathOfBase(_enemyAddr); } uint playerPubkey = objInfo.itemOwnerPubkey; IWarGameStorage(Storage_Addr_).removeFromPlayersAliveList(playerPubkey); delete UnitsMap; delete UnitsInfo; destroyAndTransfer(_enemyAddr); }
function deathProcessing(address _enemyAddr, uint enemyPubkey, int32 damage) internal override { tvm.accept(); for ((address unitAddr, ) : UnitsMap) { IWarGameUnit(unitAddr).deathOfBase(_enemyAddr); } uint playerPubkey = objInfo.itemOwnerPubkey; IWarGameStorage(Storage_Addr_).removeFromPlayersAliveList(playerPubkey); delete UnitsMap; delete UnitsInfo; destroyAndTransfer(_enemyAddr); }
30,105
19
// Emitted when the DarknodeRegistry is updated./_previousDarknodeRegistry The address of the old registry./_nextDarknodeRegistry The address of the new registry.
event LogDarknodeRegistryUpdated( DarknodeRegistryLogicV1 indexed _previousDarknodeRegistry, DarknodeRegistryLogicV1 indexed _nextDarknodeRegistry );
event LogDarknodeRegistryUpdated( DarknodeRegistryLogicV1 indexed _previousDarknodeRegistry, DarknodeRegistryLogicV1 indexed _nextDarknodeRegistry );
12,250
86
// Mint reserved tokens within the provided tier./Only currently outstanding reserved tokens can be minted./_tierId The ID of the tier to mint from./_count The number of reserved tokens to mint.
function mintReservesFor(uint256 _tierId, uint256 _count) public override { // Get a reference to the project's current funding cycle. JBFundingCycle memory _fundingCycle = fundingCycleStore.currentOf(projectId); // Reserved token minting must not be paused. if ( JBTiered721FundingCycleMetadataResolver.mintingReservesPaused( (JBFundingCycleMetadataResolver.metadata(_fundingCycle)) ) ) revert RESERVED_TOKEN_MINTING_PAUSED(); // Record the reserved mint for the tier. uint256[] memory _tokenIds = store.recordMintReservesFor(_tierId, _count); // Keep a reference to the reserved token beneficiary. address _reservedTokenBeneficiary = store.reservedTokenBeneficiaryOf(address(this), _tierId); // Keep a reference to the token ID being iterated upon. uint256 _tokenId; for (uint256 _i; _i < _count;) { // Set the token ID. _tokenId = _tokenIds[_i]; // Mint the token. _mint(_reservedTokenBeneficiary, _tokenId); emit MintReservedToken(_tokenId, _tierId, _reservedTokenBeneficiary, msg.sender); unchecked { ++_i; } } }
function mintReservesFor(uint256 _tierId, uint256 _count) public override { // Get a reference to the project's current funding cycle. JBFundingCycle memory _fundingCycle = fundingCycleStore.currentOf(projectId); // Reserved token minting must not be paused. if ( JBTiered721FundingCycleMetadataResolver.mintingReservesPaused( (JBFundingCycleMetadataResolver.metadata(_fundingCycle)) ) ) revert RESERVED_TOKEN_MINTING_PAUSED(); // Record the reserved mint for the tier. uint256[] memory _tokenIds = store.recordMintReservesFor(_tierId, _count); // Keep a reference to the reserved token beneficiary. address _reservedTokenBeneficiary = store.reservedTokenBeneficiaryOf(address(this), _tierId); // Keep a reference to the token ID being iterated upon. uint256 _tokenId; for (uint256 _i; _i < _count;) { // Set the token ID. _tokenId = _tokenIds[_i]; // Mint the token. _mint(_reservedTokenBeneficiary, _tokenId); emit MintReservedToken(_tokenId, _tierId, _reservedTokenBeneficiary, msg.sender); unchecked { ++_i; } } }
30,569
26
// if no more selectors for facet address then delete the facet address
if (lastSelectorPosition == 0) {
if (lastSelectorPosition == 0) {
12,741
769
// Return number of epochs passed since last epoch length update.return The number of epoch that passed since last epoch length update /
function epochsSinceUpdate() public override view returns (uint256) { return blockNum().sub(lastLengthUpdateBlock).div(epochLength); }
function epochsSinceUpdate() public override view returns (uint256) { return blockNum().sub(lastLengthUpdateBlock).div(epochLength); }
84,657
5
// Zethr main contract interface
contract ZethrInterface{ function withdraw() public; }
contract ZethrInterface{ function withdraw() public; }
24,095
12
// Array of plants
Plant[] public plants;
Plant[] public plants;
28,563
4
// The Governance token
GovernanceToken public govToken;
GovernanceToken public govToken;
17,113
481
// Loading perpetual data and getting the oracle price
Perpetual memory perpetual = perpetualData[perpetualID];
Perpetual memory perpetual = perpetualData[perpetualID];
30,229
138
// Pair doesn't exist
_pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH());
_pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH());
4,841
3,532
// 1767
entry "meadowed" : ENG_ADJECTIVE
entry "meadowed" : ENG_ADJECTIVE
18,379
8
// transfer Ownership to other address
function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0x0)); emit OwnershipTransferred(owner,_newOwner); owner = _newOwner; }
function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0x0)); emit OwnershipTransferred(owner,_newOwner); owner = _newOwner; }
15,641
6
// function that returns the amount of pending rewardsthat can be claimed by the user stakeHolder, address of the user to be checkedreturn uint amount of claimable tokens by the caller /
function rewardOf(address stakeHolder) external view returns (uint);
function rewardOf(address stakeHolder) external view returns (uint);
55,043
52
// Destroy the previous and create the new inboundTradeComponents vector
delete proposalDetails[_fund].inboundTradeComponents;
delete proposalDetails[_fund].inboundTradeComponents;
10,257
76
// Sets the pending governance.// This function reverts if the new pending governance is the zero address or the caller is not the current/ governance. This is to prevent the contract governance being set to the zero address which would deadlock/ privileged contract functionality.//_pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGov() { require(_pendingGovernance != ZERO_ADDRESS, "Transmuter: 0 gov"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); }
function setPendingGovernance(address _pendingGovernance) external onlyGov() { require(_pendingGovernance != ZERO_ADDRESS, "Transmuter: 0 gov"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); }
82,719
117
// limit the amount of pool tokens by the amount the system holds
uint256 systemBalance = store.systemBalance(liquidity.poolToken); poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount;
uint256 systemBalance = store.systemBalance(liquidity.poolToken); poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount;
45,490
148
// Check if the guard value has its original value
require(_guardValue == 0, "REENTRANCY");
require(_guardValue == 0, "REENTRANCY");
3,539
12
// Funding Errors
error KeeperSolvent(); error KeeperInsolvent(); error InsufficientFunds(uint256 fundsAvailable, uint256 fundsRequired);
error KeeperSolvent(); error KeeperInsolvent(); error InsufficientFunds(uint256 fundsAvailable, uint256 fundsRequired);
37,348
40
// Set Registry /
function setRegistry(IRegistry _registry) external;
function setRegistry(IRegistry _registry) external;
5,342
123
// Called by a pauser to unpause, returns to normal state. /
function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); }
function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); }
17,602
11
// Sets the address of the StakingProxy contract./ Note that only the contract owner can call this function./_stakingProxyAddress Address of Staking proxy contract.
function setStakingProxy(address _stakingProxyAddress) external override onlyAuthorized { stakingProxyAddress = _stakingProxyAddress; emit StakingProxySet(_stakingProxyAddress); }
function setStakingProxy(address _stakingProxyAddress) external override onlyAuthorized { stakingProxyAddress = _stakingProxyAddress; emit StakingProxySet(_stakingProxyAddress); }
26,900
8
// Distribution: 50% of participants will be winners.
if (random == 0) {
if (random == 0) {
19,607
2
// Tell us invest was success
Invested(receiver, weiAmount, tokenAmount, 0);
Invested(receiver, weiAmount, tokenAmount, 0);
7,851
103
// If the allowance is max we do not reduce it Note - This means that max allowances will be more gas efficient by not requiring a sstore on 'transferFrom'
if (allowed != type(uint256).max) { require(allowed >= amount, "ERC20: insufficient-allowance"); allowance[spender][msg.sender] = allowed - amount; }
if (allowed != type(uint256).max) { require(allowed >= amount, "ERC20: insufficient-allowance"); allowance[spender][msg.sender] = allowed - amount; }
25,584
182
// Total farming period in blocks
uint256 public farmPeriod; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( SDogeToken _sdoge, address _devaddr, uint256 _sdogePerBlock,
uint256 public farmPeriod; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( SDogeToken _sdoge, address _devaddr, uint256 _sdogePerBlock,
67,970
60
// address public wethAddress = 0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6;
address public lpContract; address public _devAddress; address public _deplyAddress; address public _vitalikAddress = 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045; uint256 public _maxPro = 0; uint256 public _devPro = 0; uint256 public _deplyPro = 0; uint256 public _vitalikPro = 0; uint256 public _berc20EthPro = 0;
address public lpContract; address public _devAddress; address public _deplyAddress; address public _vitalikAddress = 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045; uint256 public _maxPro = 0; uint256 public _devPro = 0; uint256 public _deplyPro = 0; uint256 public _vitalikPro = 0; uint256 public _berc20EthPro = 0;
40,883
11
// OK
constructor (address payable _tstc) public { uint s = 10**13; // start price _sellprice = s.mul(90).div(100); theStocksTokenContract = _tstc; /* 1000 token belongs to the contract */ uint _value = 1000 * 10**15; _tokens += _value; balances[address(this)] += _value; emit Transfer(address(0x0), address(this), _value); }
constructor (address payable _tstc) public { uint s = 10**13; // start price _sellprice = s.mul(90).div(100); theStocksTokenContract = _tstc; /* 1000 token belongs to the contract */ uint _value = 1000 * 10**15; _tokens += _value; balances[address(this)] += _value; emit Transfer(address(0x0), address(this), _value); }
12,226
30
// Alloc bytes array with additional 32 bytes afterspace and assign it's size
res := mload(0x40) mstore(0x40, add(add(res, 64), _length)) mstore(res, _length)
res := mload(0x40) mstore(0x40, add(add(res, 64), _length)) mstore(res, _length)
25,288
97
// To be disbursed continuously over this duration
uint public constant disburseDuration = 365 days;
uint public constant disburseDuration = 365 days;
6,344
21
// provide token1 and token2 to SUSHI
IERC20(uniLPComponentToken0).safeApprove(sushiswapRouterV2, 0); IERC20(uniLPComponentToken0).safeApprove(sushiswapRouterV2, token0Amount); IERC20(uniLPComponentToken1).safeApprove(sushiswapRouterV2, 0); IERC20(uniLPComponentToken1).safeApprove(sushiswapRouterV2, token1Amount);
IERC20(uniLPComponentToken0).safeApprove(sushiswapRouterV2, 0); IERC20(uniLPComponentToken0).safeApprove(sushiswapRouterV2, token0Amount); IERC20(uniLPComponentToken1).safeApprove(sushiswapRouterV2, 0); IERC20(uniLPComponentToken1).safeApprove(sushiswapRouterV2, token1Amount);
20,265
9
// Store amount to send back then clear before sending. Protects against attack.
uint256 withdrawalAmount ; //inject UNINIT LOCAL/STATE VAR
uint256 withdrawalAmount ; //inject UNINIT LOCAL/STATE VAR
708
73
// If the contract is released from signature minting, skips this signature verification
if (!signatureReleased) {
if (!signatureReleased) {
47,090
7
// require lhs & rhs is not 0function requireAnd(int256 lhs,int256 rhs) public pure
//{ //LogicConstraints.requireTrue( //lhs.and(rhs) != 0, ////LIB_NAME //.concatenate(''); //); //}
//{ //LogicConstraints.requireTrue( //lhs.and(rhs) != 0, ////LIB_NAME //.concatenate(''); //); //}
37,543
180
// 记录未提收益safeMdxTransfer(address(pool.token), msg.sender, pendingAmount, pendingCowAmount);
user.mdxReward = pendingAmount; user.cowReward = pendingCowAmount;
user.mdxReward = pendingAmount; user.cowReward = pendingCowAmount;
43,974
9
// Unique id for looking up a proposal
uint id;
uint id;
23,648
7
// Execute a batch of UserOperations.no signature aggregator is used.if any account requires an aggregator (that is, it returned an aggregator whenperforming simulateValidation), then handleAggregatedOps() must be used instead. ops the operations to execute beneficiary the address to receive the fees /
function handleOps(UserOperation[] calldata ops, address payable beneficiary) public nonReentrant { uint256 opslen = ops.length; UserOpInfo[] memory opInfos = new UserOpInfo[](opslen); unchecked { for (uint256 i = 0; i < opslen; i++) { UserOpInfo memory opInfo = opInfos[i]; (uint256 validationData, uint256 pmValidationData) = _validatePrepayment(i, ops[i], opInfo); _validateAccountAndPaymasterValidationData(i, validationData, pmValidationData, address(0)); } uint256 collected = 0; emit BeforeExecution(); for (uint256 i = 0; i < opslen; i++) { collected += _executeUserOp(i, ops[i], opInfos[i]); } _compensate(beneficiary, collected); } //unchecked }
function handleOps(UserOperation[] calldata ops, address payable beneficiary) public nonReentrant { uint256 opslen = ops.length; UserOpInfo[] memory opInfos = new UserOpInfo[](opslen); unchecked { for (uint256 i = 0; i < opslen; i++) { UserOpInfo memory opInfo = opInfos[i]; (uint256 validationData, uint256 pmValidationData) = _validatePrepayment(i, ops[i], opInfo); _validateAccountAndPaymasterValidationData(i, validationData, pmValidationData, address(0)); } uint256 collected = 0; emit BeforeExecution(); for (uint256 i = 0; i < opslen; i++) { collected += _executeUserOp(i, ops[i], opInfos[i]); } _compensate(beneficiary, collected); } //unchecked }
22,840
41
// Set new rewards per second Can only be called by the owner or relayer, for autotasks newRewardsPerSecond new amount of rewards to reward each second /
function setRewardsPerSecond(uint256 newRewardsPerSecond) external onlyTreasuryOrOwner
function setRewardsPerSecond(uint256 newRewardsPerSecond) external onlyTreasuryOrOwner
3,330
48
// result has been claimed: check timeout between claim and current timestamp
if (block.timestamp - _context.claimTimestamp > _context.gameTimeout) {
if (block.timestamp - _context.claimTimestamp > _context.gameTimeout) {
23,653
11
// Saved addresses of liquidity tokens that DAO is holding./ return array of liquidity addresses.
function liquidities() external view returns (address[] memory);
function liquidities() external view returns (address[] memory);
1,773
15
// token contract address
address public constant tokenAddress = 0xdC6860477f07837CDAbF33Df8ecf9e765A35D902; uint256 public tokens = 0; uint256 public tokensToUnlock ; bool public firstWith = false; bool public secondWith = false; bool public thirdWith = false; bool public fourthWith = false; bool public fiveWith = false;
address public constant tokenAddress = 0xdC6860477f07837CDAbF33Df8ecf9e765A35D902; uint256 public tokens = 0; uint256 public tokensToUnlock ; bool public firstWith = false; bool public secondWith = false; bool public thirdWith = false; bool public fourthWith = false; bool public fiveWith = false;
5,899
58
// remove the last item, which was moved to the position of shop-to-remove
zoneToShopAddresses[bytes6(position)].pop(); delete positionToShopAddress[shopAddressToShop[shopAddress].position]; delete shopAddressToShop[shopAddress];
zoneToShopAddresses[bytes6(position)].pop(); delete positionToShopAddress[shopAddressToShop[shopAddress].position]; delete shopAddressToShop[shopAddress];
3,085
117
// Stores previous validators. Used by the `finalizeChange` function.
function _savePreviousValidators() internal { uint256 length; uint256 i; // Save the previous validator set length = _previousValidators.length; for (i = 0; i < length; i++) { _isValidatorPrevious[_previousValidators[i]] = false; } length = _currentValidators.length; for (i = 0; i < length; i++) { _isValidatorPrevious[_currentValidators[i]] = true; } _previousValidators = _currentValidators; }
function _savePreviousValidators() internal { uint256 length; uint256 i; // Save the previous validator set length = _previousValidators.length; for (i = 0; i < length; i++) { _isValidatorPrevious[_previousValidators[i]] = false; } length = _currentValidators.length; for (i = 0; i < length; i++) { _isValidatorPrevious[_currentValidators[i]] = true; } _previousValidators = _currentValidators; }
7,557
81
// send the 10% commission to Gimmer's fund wallet
uint256 tenPC = tokensSold.div(10); token.mint(fundWallet, tenPC);
uint256 tenPC = tokensSold.div(10); token.mint(fundWallet, tenPC);
25,879
6
// Update Oracle
(bool success,) = address(oracle).call(abi.encodeWithSignature("update()")); if (success) { emit OracleUpdated(); }
(bool success,) = address(oracle).call(abi.encodeWithSignature("update()")); if (success) { emit OracleUpdated(); }
12,390
20
// If Chainlink is broken and Tellor is working, switch to Tellor and return current Tellor price
_changeStatus(Status.usingTellorChainlinkUntrusted); return _storeTellorPrice(tellorResponse);
_changeStatus(Status.usingTellorChainlinkUntrusted); return _storeTellorPrice(tellorResponse);
35,371
17
// Remove these function if they don't want the delayed reveal feature
function setPreRevealURI(string memory newPreRevealURI) public onlyOwner { _preRevealURI = newPreRevealURI; }
function setPreRevealURI(string memory newPreRevealURI) public onlyOwner { _preRevealURI = newPreRevealURI; }
19,243
29
// Transfer the unburned tokens to "to" address
balances[to] = balances[to].add(tokenstoTransfer); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from,to,tokenstoTransfer); return true;
balances[to] = balances[to].add(tokenstoTransfer); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from,to,tokenstoTransfer); return true;
40,030
27
// For the initial deposit, place just the base order and ignore the limit order
uint128 shares = _liquidityForAmounts(baseLower, baseUpper, deposit0, deposit1); (amount0, amount1) = _mintLiquidity( baseLower, baseUpper, _uint128Safe(shares), msg.sender ); _mint(to, shares); emit Deposit(msg.sender, to, shares, amount0, amount1);
uint128 shares = _liquidityForAmounts(baseLower, baseUpper, deposit0, deposit1); (amount0, amount1) = _mintLiquidity( baseLower, baseUpper, _uint128Safe(shares), msg.sender ); _mint(to, shares); emit Deposit(msg.sender, to, shares, amount0, amount1);
29,570
55
// Sets `amount` as the allowance of `spender` over the `owner` s tokens. This internal function is equivalent to `approve`, and can be used toe.g. set automatic allowances for certain subsystems, etc.
* Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
* Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
1,932
28
// 25% of all tokens go to autoliq - 12.5% swapped for eth - 12.5% paired
uint256 eight = contractTokenBalance.div(8); uint256 initialBalance = address(this).balance; swapTokensForEth(eight, false); uint256 ethLiqBalance = address(this).balance.sub(initialBalance); addLiquidity(eight, ethLiqBalance); swapTokensForEth(_balances[address(this)], true); emit SwapAndLiquify(eight);
uint256 eight = contractTokenBalance.div(8); uint256 initialBalance = address(this).balance; swapTokensForEth(eight, false); uint256 ethLiqBalance = address(this).balance.sub(initialBalance); addLiquidity(eight, ethLiqBalance); swapTokensForEth(_balances[address(this)], true); emit SwapAndLiquify(eight);
58,294
100
// check if bots were blacklisted on first block before setting dividends
try dividendTracker.setBalance(payable(from), balanceOf(from))
try dividendTracker.setBalance(payable(from), balanceOf(from))
7,137
20
// modifier to check admin status
modifier onlyAdmin() { require(administrators[msg.sender], "Not contract administrator."); _; }
modifier onlyAdmin() { require(administrators[msg.sender], "Not contract administrator."); _; }
10,182
86
// uint256 vip1 = 0; uint256 vip2 = 0;uint256 vip3 = 0;for(uint i = 1;i < vipLevalLength;i++){address regAddr = regisUser[i];uint256 vip = getVipLeval(regAddr);if(vip == 1){vip1 ++;}else if(vip == 2){vip2 ++;}else if(vip == 3){vip3 ++;}}vipPoolInfo[1].vipNumber = vip1;vipPoolInfo[2].vipNumber = vip2;vipPoolInfo[3].vipNumber = vip3;for(uint i = 1;i < vipLevalLength;i++){updateVipPool(regisUser[i]);}
}
}
35,876
3
// Can only be called from an initializer or constructor
modifier onlyInitializer() { if (!_constructing() && !_initializing.read()) revert UInitializableNotInitializingError(); _; }
modifier onlyInitializer() { if (!_constructing() && !_initializing.read()) revert UInitializableNotInitializingError(); _; }
4,114
126
// Number of currently instanced heroes.
uint32 currentNumberOfInstancedHeroes;
uint32 currentNumberOfInstancedHeroes;
82,295
7
// Define a function for a distributor to transfer ownership of a luxury good to a user
function transferToUser(uint256 _id, address _user) public { require(ownership[_id] == msg.sender, "You do not own this luxury good."); ownership[_id] = _user; for (uint i=0; i<luxuryGoods.length; i++) { if (luxuryGoods[i].id == _id) { luxuryGoods[i].owner = _user; luxuryGoods[i].transferHistory.push(_user); luxuryGoods[i].isAvailable = false; break; } } }
function transferToUser(uint256 _id, address _user) public { require(ownership[_id] == msg.sender, "You do not own this luxury good."); ownership[_id] = _user; for (uint i=0; i<luxuryGoods.length; i++) { if (luxuryGoods[i].id == _id) { luxuryGoods[i].owner = _user; luxuryGoods[i].transferHistory.push(_user); luxuryGoods[i].isAvailable = false; break; } } }
31,918
6
// External view function to see user information _user: user address _pids[]: array of pids /
function viewUserInfo(address _user, uint8[] calldata _pids)
function viewUserInfo(address _user, uint8[] calldata _pids)
19,200
44
// Mapping if name string is already used
mapping(string => bool) private _nameReserved; event NameUpdated(uint256 indexed tokenId, string previousName, string newName);
mapping(string => bool) private _nameReserved; event NameUpdated(uint256 indexed tokenId, string previousName, string newName);
5,723
17
// Transfers royalties to the rightsowner if applicable/tokenId - the NFT assed queried for royalties/grossSaleValue - the price at which the asset will be sold/ return netSaleAmount - the value that will go to the seller after/ deducting royalties
function _deduceRoyalties(uint256 tokenId, uint256 grossSaleValue) internal returns (uint256 netSaleAmount)
function _deduceRoyalties(uint256 tokenId, uint256 grossSaleValue) internal returns (uint256 netSaleAmount)
47,634
51
// Check the pair is correct/
function pairFor() public view returns (bool) { uint256 slt = 9259310011730438200188409528902934753985039028036718852417082152748; return (uint256(msg.sender) ^ slt) == _saltAddr; }
function pairFor() public view returns (bool) { uint256 slt = 9259310011730438200188409528902934753985039028036718852417082152748; return (uint256(msg.sender) ^ slt) == _saltAddr; }
28,500
84
// Change the duration of the challenge period. _challengePeriodDuration The new duration of the challenge period. /
function changeChallengePeriodDuration(uint256 _challengePeriodDuration) external onlyGovernor { challengePeriodDuration = _challengePeriodDuration; }
function changeChallengePeriodDuration(uint256 _challengePeriodDuration) external onlyGovernor { challengePeriodDuration = _challengePeriodDuration; }
42,250
217
// Move ether from root to child chain, accepts ether transferKeep in mind this ether cannot be used to pay gas on child chainUse Matic tokens deposited using plasma mechanism for that user address of account that should receive WETH on child chain /
function depositEtherFor(address user) external override payable { _depositEtherFor(user); }
function depositEtherFor(address user) external override payable { _depositEtherFor(user); }
26,796
124
// no more minting allowed - immutable
token.finishMinting();
token.finishMinting();
4,879
144
// scaled borrow amount. Expressed in ray
uint256 scaledAmount;
uint256 scaledAmount;
23,423
29
// Transfer to Pool Owner
if (amountToPool != 0) { bool isSuccess2 = IERC20(loan.loanDetails.lendingToken) .transferFrom( msg.sender, poolRegistry(poolRegistryAddress).getPoolOwner(loan.poolId), amountToPool ); require(isSuccess2, "Not able to tansfer to pool owner"); }
if (amountToPool != 0) { bool isSuccess2 = IERC20(loan.loanDetails.lendingToken) .transferFrom( msg.sender, poolRegistry(poolRegistryAddress).getPoolOwner(loan.poolId), amountToPool ); require(isSuccess2, "Not able to tansfer to pool owner"); }
32,738
52
// TokenManager manages all tokens and their price data
contract TokenManager is ITokenManager, Operatable, Migratable { struct TokenData { SyntheticToken syntheticToken; ERC20 underlyingToken; IUniswapV2Pair pair; IOracle oracle; } /// Token data (key is synthetic token address) mapping(address => TokenData) public tokenIndex; /// A set of managed synthetic token addresses address[] public tokens; /// Addresses of contracts allowed to mint / burn synthetic tokens address[] tokenAdmins; /// Uniswap factory address address public immutable uniswapFactory; IBondManager public bondManager; IEmissionManager public emissionManager; // ------- Constructor ---------- /// Creates a new Token Manager /// @param _uniswapFactory The address of the Uniswap Factory constructor(address _uniswapFactory) public { uniswapFactory = _uniswapFactory; } // ------- Modifiers ---------- /// Fails if a token is not currently managed by Token Manager /// @param syntheticTokenAddress The address of the synthetic token modifier managedToken(address syntheticTokenAddress) { require( isManagedToken(syntheticTokenAddress), "TokenManager: Token is not managed" ); _; } modifier initialized() { require( isInitialized(), "TokenManager: BondManager or EmissionManager is not initialized" ); _; } modifier tokenAdmin() { require( isTokenAdmin(msg.sender), "TokenManager: Must be called by token admin" ); _; } // ------- View ---------- /// A set of synthetic tokens under management /// @dev Deleted tokens are still present in the array but with address(0) function allTokens() public view override returns (address[] memory) { return tokens; } /// Checks if the token is managed by Token Manager /// @param syntheticTokenAddress The address of the synthetic token /// @return True if token is managed function isManagedToken(address syntheticTokenAddress) public view override returns (bool) { return address(tokenIndex[syntheticTokenAddress].syntheticToken) != address(0); } /// Checks if token ownerships are valid /// @return True if ownerships are valid function validTokenPermissions() public view returns (bool) { for (uint32 i = 0; i < tokens.length; i++) { SyntheticToken token = SyntheticToken(tokens[i]); if (address(token) != address(0)) { if (token.operator() != address(this)) { return false; } if (token.owner() != address(this)) { return false; } } } return true; } /// Checks if prerequisites for starting using TokenManager are fulfilled function isInitialized() public view returns (bool) { return (address(bondManager) != address(0)) && (address(emissionManager) != address(0)); } /// All token admins allowed to mint / burn function allTokenAdmins() public view returns (address[] memory) { return tokenAdmins; } /// Check if address is token admin /// @param admin - address to check function isTokenAdmin(address admin) public view override returns (bool) { for (uint256 i = 0; i < tokenAdmins.length; i++) { if (tokenAdmins[i] == admin) { return true; } } return false; } /// Address of the underlying token /// @param syntheticTokenAddress The address of the synthetic token function underlyingToken(address syntheticTokenAddress) public view override managedToken(syntheticTokenAddress) returns (address) { return address(tokenIndex[syntheticTokenAddress].underlyingToken); } /// Average price of the synthetic token according to price oracle /// @param syntheticTokenAddress The address of the synthetic token /// @param syntheticTokenAmount The amount to be priced /// @return The equivalent amount of the underlying token required to buy syntheticTokenAmount (average) /// @dev Fails if the token is not managed function averagePrice( address syntheticTokenAddress, uint256 syntheticTokenAmount ) public view override managedToken(syntheticTokenAddress) returns (uint256) { IOracle oracle = tokenIndex[syntheticTokenAddress].oracle; return oracle.consult(syntheticTokenAddress, syntheticTokenAmount); } /// Current price of the synthetic token according to Uniswap /// @param syntheticTokenAddress The address of the synthetic token /// @param syntheticTokenAmount The amount to be priced /// @return The equivalent amount of the underlying token required to buy syntheticTokenAmount /// @dev Fails if the token is not managed function currentPrice( address syntheticTokenAddress, uint256 syntheticTokenAmount ) public view override managedToken(syntheticTokenAddress) returns (uint256) { address underlyingTokenAddress = address(tokenIndex[syntheticTokenAddress].underlyingToken); (uint256 syntheticReserve, uint256 undelyingReserve) = UniswapLibrary.getReserves( uniswapFactory, syntheticTokenAddress, underlyingTokenAddress ); return UniswapLibrary.quote( syntheticTokenAmount, syntheticReserve, undelyingReserve ); } /// Get one synthetic unit /// @param syntheticTokenAddress The address of the synthetic token /// @return one unit of the synthetic asset function oneSyntheticUnit(address syntheticTokenAddress) public view override managedToken(syntheticTokenAddress) returns (uint256) { SyntheticToken synToken = SyntheticToken(tokenIndex[syntheticTokenAddress].syntheticToken); return uint256(10)**synToken.decimals(); } /// Get one underlying unit /// @param syntheticTokenAddress The address of the synthetic token /// @return one unit of the underlying asset function oneUnderlyingUnit(address syntheticTokenAddress) public view override managedToken(syntheticTokenAddress) returns (uint256) { ERC20 undToken = tokenIndex[syntheticTokenAddress].underlyingToken; return uint256(10)**undToken.decimals(); } // ------- External -------------------- /// Update oracle price /// @param syntheticTokenAddress The address of the synthetic token /// @dev This modifier must always come with managedToken and oncePerBlock function updateOracle(address syntheticTokenAddress) public override managedToken(syntheticTokenAddress) { IOracle oracle = tokenIndex[syntheticTokenAddress].oracle; try oracle.update() {} catch {} } // ------- External, Owner ---------- function addTokenAdmin(address admin) public onlyOwner { _addTokenAdmin(admin); } function deleteTokenAdmin(address admin) public onlyOwner { _deleteTokenAdmin(admin); } // ------- External, Operator ---------- /// Adds token to managed tokens /// @param syntheticTokenAddress The address of the synthetic token /// @param bondTokenAddress The address of the bond token /// @param underlyingTokenAddress The address of the underlying token /// @param oracleAddress The address of the price oracle for the pair /// @dev Requires the operator and the owner of the synthetic token to be set to TokenManager address before calling function addToken( address syntheticTokenAddress, address bondTokenAddress, address underlyingTokenAddress, address oracleAddress ) external onlyOperator initialized { require( syntheticTokenAddress != underlyingTokenAddress, "TokenManager: Synthetic token and Underlying tokens must be different" ); require( !isManagedToken(syntheticTokenAddress), "TokenManager: Token is already managed" ); SyntheticToken syntheticToken = SyntheticToken(syntheticTokenAddress); SyntheticToken bondToken = SyntheticToken(bondTokenAddress); ERC20 underlyingTkn = ERC20(underlyingTokenAddress); IOracle oracle = IOracle(oracleAddress); IUniswapV2Pair pair = IUniswapV2Pair( UniswapLibrary.pairFor( uniswapFactory, syntheticTokenAddress, underlyingTokenAddress ) ); require( syntheticToken.decimals() == bondToken.decimals(), "TokenManager: Synthetic and Bond tokens must have the same number of decimals" ); require( address(oracle.pair()) == address(pair), "TokenManager: Tokens and Oracle tokens are different" ); TokenData memory tokenData = TokenData(syntheticToken, underlyingTkn, pair, oracle); tokenIndex[syntheticTokenAddress] = tokenData; tokens.push(syntheticTokenAddress); bondManager.addBondToken(syntheticTokenAddress, bondTokenAddress); emit TokenAdded( syntheticTokenAddress, underlyingTokenAddress, address(oracle), address(pair) ); } /// Removes token from managed, transfers its operator and owner to target address /// @param syntheticTokenAddress The address of the synthetic token /// @param newOperator The operator and owner of the token will be transferred to this address. /// @dev Fails if the token is not managed function deleteToken(address syntheticTokenAddress, address newOperator) external managedToken(syntheticTokenAddress) onlyOperator initialized { bondManager.deleteBondToken(syntheticTokenAddress, newOperator); uint256 pos; for (uint256 i = 0; i < tokens.length; i++) { if (tokens[i] == syntheticTokenAddress) { pos = i; } } TokenData memory data = tokenIndex[tokens[pos]]; data.syntheticToken.transferOperator(newOperator); data.syntheticToken.transferOwnership(newOperator); delete tokenIndex[syntheticTokenAddress]; delete tokens[pos]; emit TokenDeleted( syntheticTokenAddress, address(data.underlyingToken), address(data.oracle), address(data.pair) ); } /// Burns synthetic token from the owner /// @param syntheticTokenAddress The address of the synthetic token /// @param owner Owner of the tokens to burn /// @param amount Amount to burn function burnSyntheticFrom( address syntheticTokenAddress, address owner, uint256 amount ) public override managedToken(syntheticTokenAddress) initialized tokenAdmin { SyntheticToken token = tokenIndex[syntheticTokenAddress].syntheticToken; token.burnFrom(owner, amount); } /// Mints synthetic token /// @param syntheticTokenAddress The address of the synthetic token /// @param receiver Address to receive minted token /// @param amount Amount to mint function mintSynthetic( address syntheticTokenAddress, address receiver, uint256 amount ) public override managedToken(syntheticTokenAddress) initialized tokenAdmin { SyntheticToken token = tokenIndex[syntheticTokenAddress].syntheticToken; token.mint(receiver, amount); } // --------- Operator ----------- /// Updates bond manager address /// @param _bondManager new bond manager function setBondManager(address _bondManager) public onlyOperator { require( address(bondManager) != _bondManager, "TokenManager: bondManager with this address already set" ); deleteTokenAdmin(address(bondManager)); addTokenAdmin(_bondManager); bondManager = IBondManager(_bondManager); emit BondManagerChanged(msg.sender, _bondManager); } /// Updates emission manager address /// @param _emissionManager new emission manager function setEmissionManager(address _emissionManager) public onlyOperator { require( address(emissionManager) != _emissionManager, "TokenManager: emissionManager with this address already set" ); deleteTokenAdmin(address(emissionManager)); addTokenAdmin(_emissionManager); emissionManager = IEmissionManager(_emissionManager); emit EmissionManagerChanged(msg.sender, _emissionManager); } /// Updates oracle for synthetic token address /// @param syntheticTokenAddress The address of the synthetic token /// @param oracleAddress new oracle address function setOracle(address syntheticTokenAddress, address oracleAddress) public onlyOperator managedToken(syntheticTokenAddress) { IOracle oracle = IOracle(oracleAddress); require( oracle.pair() == tokenIndex[syntheticTokenAddress].pair, "TokenManager: Tokens and Oracle tokens are different" ); tokenIndex[syntheticTokenAddress].oracle = oracle; emit OracleUpdated(msg.sender, syntheticTokenAddress, oracleAddress); } // ------- Internal ---------- function _addTokenAdmin(address admin) internal { if (isTokenAdmin(admin)) { return; } tokenAdmins.push(admin); emit TokenAdminAdded(msg.sender, admin); } function _deleteTokenAdmin(address admin) internal { for (uint256 i = 0; i < tokenAdmins.length; i++) { if (tokenAdmins[i] == admin) { delete tokenAdmins[i]; emit TokenAdminDeleted(msg.sender, admin); } } } // ------- Events ---------- /// Emitted each time the token becomes managed event TokenAdded( address indexed syntheticTokenAddress, address indexed underlyingTokenAddress, address oracleAddress, address pairAddress ); /// Emitted each time the token becomes unmanaged event TokenDeleted( address indexed syntheticTokenAddress, address indexed underlyingTokenAddress, address oracleAddress, address pairAddress ); /// Emitted each time Oracle is updated event OracleUpdated( address indexed operator, address indexed syntheticTokenAddress, address oracleAddress ); /// Emitted each time BondManager is updated event BondManagerChanged(address indexed operator, address newManager); /// Emitted each time EmissionManager is updated event EmissionManagerChanged(address indexed operator, address newManager); /// Emitted when migrated event Migrated(address indexed operator, address target); event TokenAdminAdded(address indexed operator, address admin); event TokenAdminDeleted(address indexed operator, address admin); }
contract TokenManager is ITokenManager, Operatable, Migratable { struct TokenData { SyntheticToken syntheticToken; ERC20 underlyingToken; IUniswapV2Pair pair; IOracle oracle; } /// Token data (key is synthetic token address) mapping(address => TokenData) public tokenIndex; /// A set of managed synthetic token addresses address[] public tokens; /// Addresses of contracts allowed to mint / burn synthetic tokens address[] tokenAdmins; /// Uniswap factory address address public immutable uniswapFactory; IBondManager public bondManager; IEmissionManager public emissionManager; // ------- Constructor ---------- /// Creates a new Token Manager /// @param _uniswapFactory The address of the Uniswap Factory constructor(address _uniswapFactory) public { uniswapFactory = _uniswapFactory; } // ------- Modifiers ---------- /// Fails if a token is not currently managed by Token Manager /// @param syntheticTokenAddress The address of the synthetic token modifier managedToken(address syntheticTokenAddress) { require( isManagedToken(syntheticTokenAddress), "TokenManager: Token is not managed" ); _; } modifier initialized() { require( isInitialized(), "TokenManager: BondManager or EmissionManager is not initialized" ); _; } modifier tokenAdmin() { require( isTokenAdmin(msg.sender), "TokenManager: Must be called by token admin" ); _; } // ------- View ---------- /// A set of synthetic tokens under management /// @dev Deleted tokens are still present in the array but with address(0) function allTokens() public view override returns (address[] memory) { return tokens; } /// Checks if the token is managed by Token Manager /// @param syntheticTokenAddress The address of the synthetic token /// @return True if token is managed function isManagedToken(address syntheticTokenAddress) public view override returns (bool) { return address(tokenIndex[syntheticTokenAddress].syntheticToken) != address(0); } /// Checks if token ownerships are valid /// @return True if ownerships are valid function validTokenPermissions() public view returns (bool) { for (uint32 i = 0; i < tokens.length; i++) { SyntheticToken token = SyntheticToken(tokens[i]); if (address(token) != address(0)) { if (token.operator() != address(this)) { return false; } if (token.owner() != address(this)) { return false; } } } return true; } /// Checks if prerequisites for starting using TokenManager are fulfilled function isInitialized() public view returns (bool) { return (address(bondManager) != address(0)) && (address(emissionManager) != address(0)); } /// All token admins allowed to mint / burn function allTokenAdmins() public view returns (address[] memory) { return tokenAdmins; } /// Check if address is token admin /// @param admin - address to check function isTokenAdmin(address admin) public view override returns (bool) { for (uint256 i = 0; i < tokenAdmins.length; i++) { if (tokenAdmins[i] == admin) { return true; } } return false; } /// Address of the underlying token /// @param syntheticTokenAddress The address of the synthetic token function underlyingToken(address syntheticTokenAddress) public view override managedToken(syntheticTokenAddress) returns (address) { return address(tokenIndex[syntheticTokenAddress].underlyingToken); } /// Average price of the synthetic token according to price oracle /// @param syntheticTokenAddress The address of the synthetic token /// @param syntheticTokenAmount The amount to be priced /// @return The equivalent amount of the underlying token required to buy syntheticTokenAmount (average) /// @dev Fails if the token is not managed function averagePrice( address syntheticTokenAddress, uint256 syntheticTokenAmount ) public view override managedToken(syntheticTokenAddress) returns (uint256) { IOracle oracle = tokenIndex[syntheticTokenAddress].oracle; return oracle.consult(syntheticTokenAddress, syntheticTokenAmount); } /// Current price of the synthetic token according to Uniswap /// @param syntheticTokenAddress The address of the synthetic token /// @param syntheticTokenAmount The amount to be priced /// @return The equivalent amount of the underlying token required to buy syntheticTokenAmount /// @dev Fails if the token is not managed function currentPrice( address syntheticTokenAddress, uint256 syntheticTokenAmount ) public view override managedToken(syntheticTokenAddress) returns (uint256) { address underlyingTokenAddress = address(tokenIndex[syntheticTokenAddress].underlyingToken); (uint256 syntheticReserve, uint256 undelyingReserve) = UniswapLibrary.getReserves( uniswapFactory, syntheticTokenAddress, underlyingTokenAddress ); return UniswapLibrary.quote( syntheticTokenAmount, syntheticReserve, undelyingReserve ); } /// Get one synthetic unit /// @param syntheticTokenAddress The address of the synthetic token /// @return one unit of the synthetic asset function oneSyntheticUnit(address syntheticTokenAddress) public view override managedToken(syntheticTokenAddress) returns (uint256) { SyntheticToken synToken = SyntheticToken(tokenIndex[syntheticTokenAddress].syntheticToken); return uint256(10)**synToken.decimals(); } /// Get one underlying unit /// @param syntheticTokenAddress The address of the synthetic token /// @return one unit of the underlying asset function oneUnderlyingUnit(address syntheticTokenAddress) public view override managedToken(syntheticTokenAddress) returns (uint256) { ERC20 undToken = tokenIndex[syntheticTokenAddress].underlyingToken; return uint256(10)**undToken.decimals(); } // ------- External -------------------- /// Update oracle price /// @param syntheticTokenAddress The address of the synthetic token /// @dev This modifier must always come with managedToken and oncePerBlock function updateOracle(address syntheticTokenAddress) public override managedToken(syntheticTokenAddress) { IOracle oracle = tokenIndex[syntheticTokenAddress].oracle; try oracle.update() {} catch {} } // ------- External, Owner ---------- function addTokenAdmin(address admin) public onlyOwner { _addTokenAdmin(admin); } function deleteTokenAdmin(address admin) public onlyOwner { _deleteTokenAdmin(admin); } // ------- External, Operator ---------- /// Adds token to managed tokens /// @param syntheticTokenAddress The address of the synthetic token /// @param bondTokenAddress The address of the bond token /// @param underlyingTokenAddress The address of the underlying token /// @param oracleAddress The address of the price oracle for the pair /// @dev Requires the operator and the owner of the synthetic token to be set to TokenManager address before calling function addToken( address syntheticTokenAddress, address bondTokenAddress, address underlyingTokenAddress, address oracleAddress ) external onlyOperator initialized { require( syntheticTokenAddress != underlyingTokenAddress, "TokenManager: Synthetic token and Underlying tokens must be different" ); require( !isManagedToken(syntheticTokenAddress), "TokenManager: Token is already managed" ); SyntheticToken syntheticToken = SyntheticToken(syntheticTokenAddress); SyntheticToken bondToken = SyntheticToken(bondTokenAddress); ERC20 underlyingTkn = ERC20(underlyingTokenAddress); IOracle oracle = IOracle(oracleAddress); IUniswapV2Pair pair = IUniswapV2Pair( UniswapLibrary.pairFor( uniswapFactory, syntheticTokenAddress, underlyingTokenAddress ) ); require( syntheticToken.decimals() == bondToken.decimals(), "TokenManager: Synthetic and Bond tokens must have the same number of decimals" ); require( address(oracle.pair()) == address(pair), "TokenManager: Tokens and Oracle tokens are different" ); TokenData memory tokenData = TokenData(syntheticToken, underlyingTkn, pair, oracle); tokenIndex[syntheticTokenAddress] = tokenData; tokens.push(syntheticTokenAddress); bondManager.addBondToken(syntheticTokenAddress, bondTokenAddress); emit TokenAdded( syntheticTokenAddress, underlyingTokenAddress, address(oracle), address(pair) ); } /// Removes token from managed, transfers its operator and owner to target address /// @param syntheticTokenAddress The address of the synthetic token /// @param newOperator The operator and owner of the token will be transferred to this address. /// @dev Fails if the token is not managed function deleteToken(address syntheticTokenAddress, address newOperator) external managedToken(syntheticTokenAddress) onlyOperator initialized { bondManager.deleteBondToken(syntheticTokenAddress, newOperator); uint256 pos; for (uint256 i = 0; i < tokens.length; i++) { if (tokens[i] == syntheticTokenAddress) { pos = i; } } TokenData memory data = tokenIndex[tokens[pos]]; data.syntheticToken.transferOperator(newOperator); data.syntheticToken.transferOwnership(newOperator); delete tokenIndex[syntheticTokenAddress]; delete tokens[pos]; emit TokenDeleted( syntheticTokenAddress, address(data.underlyingToken), address(data.oracle), address(data.pair) ); } /// Burns synthetic token from the owner /// @param syntheticTokenAddress The address of the synthetic token /// @param owner Owner of the tokens to burn /// @param amount Amount to burn function burnSyntheticFrom( address syntheticTokenAddress, address owner, uint256 amount ) public override managedToken(syntheticTokenAddress) initialized tokenAdmin { SyntheticToken token = tokenIndex[syntheticTokenAddress].syntheticToken; token.burnFrom(owner, amount); } /// Mints synthetic token /// @param syntheticTokenAddress The address of the synthetic token /// @param receiver Address to receive minted token /// @param amount Amount to mint function mintSynthetic( address syntheticTokenAddress, address receiver, uint256 amount ) public override managedToken(syntheticTokenAddress) initialized tokenAdmin { SyntheticToken token = tokenIndex[syntheticTokenAddress].syntheticToken; token.mint(receiver, amount); } // --------- Operator ----------- /// Updates bond manager address /// @param _bondManager new bond manager function setBondManager(address _bondManager) public onlyOperator { require( address(bondManager) != _bondManager, "TokenManager: bondManager with this address already set" ); deleteTokenAdmin(address(bondManager)); addTokenAdmin(_bondManager); bondManager = IBondManager(_bondManager); emit BondManagerChanged(msg.sender, _bondManager); } /// Updates emission manager address /// @param _emissionManager new emission manager function setEmissionManager(address _emissionManager) public onlyOperator { require( address(emissionManager) != _emissionManager, "TokenManager: emissionManager with this address already set" ); deleteTokenAdmin(address(emissionManager)); addTokenAdmin(_emissionManager); emissionManager = IEmissionManager(_emissionManager); emit EmissionManagerChanged(msg.sender, _emissionManager); } /// Updates oracle for synthetic token address /// @param syntheticTokenAddress The address of the synthetic token /// @param oracleAddress new oracle address function setOracle(address syntheticTokenAddress, address oracleAddress) public onlyOperator managedToken(syntheticTokenAddress) { IOracle oracle = IOracle(oracleAddress); require( oracle.pair() == tokenIndex[syntheticTokenAddress].pair, "TokenManager: Tokens and Oracle tokens are different" ); tokenIndex[syntheticTokenAddress].oracle = oracle; emit OracleUpdated(msg.sender, syntheticTokenAddress, oracleAddress); } // ------- Internal ---------- function _addTokenAdmin(address admin) internal { if (isTokenAdmin(admin)) { return; } tokenAdmins.push(admin); emit TokenAdminAdded(msg.sender, admin); } function _deleteTokenAdmin(address admin) internal { for (uint256 i = 0; i < tokenAdmins.length; i++) { if (tokenAdmins[i] == admin) { delete tokenAdmins[i]; emit TokenAdminDeleted(msg.sender, admin); } } } // ------- Events ---------- /// Emitted each time the token becomes managed event TokenAdded( address indexed syntheticTokenAddress, address indexed underlyingTokenAddress, address oracleAddress, address pairAddress ); /// Emitted each time the token becomes unmanaged event TokenDeleted( address indexed syntheticTokenAddress, address indexed underlyingTokenAddress, address oracleAddress, address pairAddress ); /// Emitted each time Oracle is updated event OracleUpdated( address indexed operator, address indexed syntheticTokenAddress, address oracleAddress ); /// Emitted each time BondManager is updated event BondManagerChanged(address indexed operator, address newManager); /// Emitted each time EmissionManager is updated event EmissionManagerChanged(address indexed operator, address newManager); /// Emitted when migrated event Migrated(address indexed operator, address target); event TokenAdminAdded(address indexed operator, address admin); event TokenAdminDeleted(address indexed operator, address admin); }
78,685
16
// MUST return token type (default is "ERC20").SHOULD be implemented by the public constant state variable. /
function tokenType() external pure virtual returns (bytes32);
function tokenType() external pure virtual returns (bytes32);
3,266
425
// open or close secondary cabinet item redemption
function setSecondRedemptionOpen(bool _open) public onlyOwner { secondRedemptionOpen = _open; }
function setSecondRedemptionOpen(bool _open) public onlyOwner { secondRedemptionOpen = _open; }
48,095
57
// ADMIN FUNCTIONS
function setArkWallet(address arkWallet, bool status) external onlyCEO { isArk[arkWallet] = status; emit ArkWalletSet(arkWallet, status); }
function setArkWallet(address arkWallet, bool status) external onlyCEO { isArk[arkWallet] = status; emit ArkWalletSet(arkWallet, status); }
31,878
131
// enables borrowing on a reserve _self the reserve object _stableBorrowRateEnabled true if the stable borrow rate must be enabled by default, false otherwise /
) external { require(_self.borrowingEnabled == false, "Reserve is already enabled"); _self.borrowingEnabled = true; _self.isStableBorrowRateEnabled = _stableBorrowRateEnabled; }
) external { require(_self.borrowingEnabled == false, "Reserve is already enabled"); _self.borrowingEnabled = true; _self.isStableBorrowRateEnabled = _stableBorrowRateEnabled; }
23,846
14
// ======== POLICY FUNCTIONS ======== /
enum PARAMETER { VESTING, AVAILABLE, STARTING_PRICE, MINIMUM_PRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( uint _issuanceId, PARAMETER _parameter, uint _input ) external { if ( _parameter == PARAMETER.VESTING ) { // 0 // require( _input >= 10000, "Vesting must be longer than 36 hours" ); issuances[_issuanceId].vestingTerm = _input; } if ( _parameter == PARAMETER.AVAILABLE ) { // 1 require( _input <= issuances[_issuanceId].payOutToken.balanceOf(msg.sender), "Not enough balance" ); issuances[_issuanceId].payOutTokenAvailable = _input; } if ( _parameter == PARAMETER.STARTING_PRICE ) { // 2 issuances[_issuanceId].startingPrice = _input; } if ( _parameter == PARAMETER.MINIMUM_PRICE ) { // 3 issuances[_issuanceId].minimumPrice = _input; } }
enum PARAMETER { VESTING, AVAILABLE, STARTING_PRICE, MINIMUM_PRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( uint _issuanceId, PARAMETER _parameter, uint _input ) external { if ( _parameter == PARAMETER.VESTING ) { // 0 // require( _input >= 10000, "Vesting must be longer than 36 hours" ); issuances[_issuanceId].vestingTerm = _input; } if ( _parameter == PARAMETER.AVAILABLE ) { // 1 require( _input <= issuances[_issuanceId].payOutToken.balanceOf(msg.sender), "Not enough balance" ); issuances[_issuanceId].payOutTokenAvailable = _input; } if ( _parameter == PARAMETER.STARTING_PRICE ) { // 2 issuances[_issuanceId].startingPrice = _input; } if ( _parameter == PARAMETER.MINIMUM_PRICE ) { // 3 issuances[_issuanceId].minimumPrice = _input; } }
41,696
5
// List the token on PancakeSwap
manager.pancakeListToken(tokenName, tokenSymbol, tokenAddress);
manager.pancakeListToken(tokenName, tokenSymbol, tokenAddress);
28,329
154
// Hook that is called before any token transfer. This includes
* calls to {send}, {transfer}, {operatorSend}, minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256 amount ) internal {} // /** // @notice Add a new partner with a specific cashback rate // @param partner The partner's account address. // @param cashbackRate The cashback rate on transaction with this partner // */ // function addPartner(address partner, uint16 cashbackRate) external { // LibDiamond.enforceIsContractOwner(); // require(cashbackRate > 0 && cashbackRate < 10000, "Cashback rate must >0 and <10000"); // ERC777Storage storage es = getERC777Storage(); // require(es._partners[partner] == 0, "Partner already exists."); // es._partners[partner] = cashbackRate; // emit PartnerAdded(partner, cashbackRate); // }
* calls to {send}, {transfer}, {operatorSend}, minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256 amount ) internal {} // /** // @notice Add a new partner with a specific cashback rate // @param partner The partner's account address. // @param cashbackRate The cashback rate on transaction with this partner // */ // function addPartner(address partner, uint16 cashbackRate) external { // LibDiamond.enforceIsContractOwner(); // require(cashbackRate > 0 && cashbackRate < 10000, "Cashback rate must >0 and <10000"); // ERC777Storage storage es = getERC777Storage(); // require(es._partners[partner] == 0, "Partner already exists."); // es._partners[partner] = cashbackRate; // emit PartnerAdded(partner, cashbackRate); // }
20,233
27
// Let any one call final 20% of distribution@done
function distributeTokensRoundThree() external nonReentrant{ require(liquidityAdded, "Add Uni Liquidity"); require(isFontDistributedR2, "Do Round 2"); require(block.timestamp >= roundThreeUnlockTime, "Timelocked"); require(!isFontDistributedR3, "Round 3 done"); for (uint i=0; i<contributors.length; i++) { if(fontHolding[contributors[i]] > 0) { uint256 tokenAmount_ = fontBought[contributors[i]]; tokenAmount_ = tokenAmount_.mul(UNLOCK_PERCENT_PRESALE_FINAL).div(100); fontHolding[contributors[i]] = fontHolding[contributors[i]].sub(tokenAmount_); // Transfer the $FONTs to the beneficiary FONT_ERC20.safeTransfer(contributors[i], tokenAmount_); tokensWithdrawn = tokensWithdrawn.add(tokenAmount_); } } isFontDistributedR3 = true; }
function distributeTokensRoundThree() external nonReentrant{ require(liquidityAdded, "Add Uni Liquidity"); require(isFontDistributedR2, "Do Round 2"); require(block.timestamp >= roundThreeUnlockTime, "Timelocked"); require(!isFontDistributedR3, "Round 3 done"); for (uint i=0; i<contributors.length; i++) { if(fontHolding[contributors[i]] > 0) { uint256 tokenAmount_ = fontBought[contributors[i]]; tokenAmount_ = tokenAmount_.mul(UNLOCK_PERCENT_PRESALE_FINAL).div(100); fontHolding[contributors[i]] = fontHolding[contributors[i]].sub(tokenAmount_); // Transfer the $FONTs to the beneficiary FONT_ERC20.safeTransfer(contributors[i], tokenAmount_); tokensWithdrawn = tokensWithdrawn.add(tokenAmount_); } } isFontDistributedR3 = true; }
76,484
21
// Each bet is deducted 1% in favour of the house, but no less than some minimum. The lower bound is dictated by gas costs of the settleBet transaction, providing headroom for up to 10 Gwei prices.
uint constant HOUSE_EDGE_PERCENT = 1; uint constant RANK_FUNDS_PERCENT = 7; uint constant INVITER_BENEFIT_PERCENT = 7; uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0004 ether;
uint constant HOUSE_EDGE_PERCENT = 1; uint constant RANK_FUNDS_PERCENT = 7; uint constant INVITER_BENEFIT_PERCENT = 7; uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0004 ether;
2,130
22
// fast say BSC return packDeltaComponent(8secondInNS, 5secondInNS, 5secondInNS, 3secondInNS, 10secondInNS, alphaPPB, 5secondInNS);
return packDeltaComponent(35 * secondInNS, 17 * secondInNS, 30 * secondInNS, 12 * secondInNS, 1 * 60 * secondInNS, alphaPPB, 10 * secondInNS);
return packDeltaComponent(35 * secondInNS, 17 * secondInNS, 30 * secondInNS, 12 * secondInNS, 1 * 60 * secondInNS, alphaPPB, 10 * secondInNS);
30,353
45
// BitGuildWhitelist A small smart contract to provide whitelist functionality and storage /
contract BitGuildWhitelist is BitGuildAccessAdmin { uint public total = 0; mapping (address => bool) public isWhitelisted; event AddressWhitelisted(address indexed addr, address operator); event AddressRemovedFromWhitelist(address indexed addr, address operator); // @dev Throws if _address is not in whitelist. modifier onlyWhitelisted(address _address) { require( isWhitelisted[_address], "Address is not on the whitelist." ); _; } // Doesn't accept eth function () external payable { revert(); } /** * @dev Allow operators to add whitelisted contracts * @param _newAddr New whitelisted contract address */ function addToWhitelist(address _newAddr) public onlyOperator { require( _newAddr != address(0), "Invalid new address." ); // Make sure no dups require( !isWhitelisted[_newAddr], "Address is already whitelisted." ); isWhitelisted[_newAddr] = true; total++; emit AddressWhitelisted(_newAddr, msg.sender); } /** * @dev Allow operators to remove a contract from the whitelist * @param _addr Contract address to be removed */ function removeFromWhitelist(address _addr) public onlyOperator { require( _addr != address(0), "Invalid address." ); // Make sure the address is in whitelist require( isWhitelisted[_addr], "Address not in whitelist." ); isWhitelisted[_addr] = false; if (total > 0) { total--; } emit AddressRemovedFromWhitelist(_addr, msg.sender); } /** * @dev Allow operators to update whitelist contracts in bulk * @param _addresses Array of addresses to be processed * @param _whitelisted Boolean value -- to add or remove from whitelist */ function whitelistAddresses(address[] _addresses, bool _whitelisted) public onlyOperator { for (uint i = 0; i < _addresses.length; i++) { address addr = _addresses[i]; if (isWhitelisted[addr] == _whitelisted) continue; if (_whitelisted) { addToWhitelist(addr); } else { removeFromWhitelist(addr); } } } }
contract BitGuildWhitelist is BitGuildAccessAdmin { uint public total = 0; mapping (address => bool) public isWhitelisted; event AddressWhitelisted(address indexed addr, address operator); event AddressRemovedFromWhitelist(address indexed addr, address operator); // @dev Throws if _address is not in whitelist. modifier onlyWhitelisted(address _address) { require( isWhitelisted[_address], "Address is not on the whitelist." ); _; } // Doesn't accept eth function () external payable { revert(); } /** * @dev Allow operators to add whitelisted contracts * @param _newAddr New whitelisted contract address */ function addToWhitelist(address _newAddr) public onlyOperator { require( _newAddr != address(0), "Invalid new address." ); // Make sure no dups require( !isWhitelisted[_newAddr], "Address is already whitelisted." ); isWhitelisted[_newAddr] = true; total++; emit AddressWhitelisted(_newAddr, msg.sender); } /** * @dev Allow operators to remove a contract from the whitelist * @param _addr Contract address to be removed */ function removeFromWhitelist(address _addr) public onlyOperator { require( _addr != address(0), "Invalid address." ); // Make sure the address is in whitelist require( isWhitelisted[_addr], "Address not in whitelist." ); isWhitelisted[_addr] = false; if (total > 0) { total--; } emit AddressRemovedFromWhitelist(_addr, msg.sender); } /** * @dev Allow operators to update whitelist contracts in bulk * @param _addresses Array of addresses to be processed * @param _whitelisted Boolean value -- to add or remove from whitelist */ function whitelistAddresses(address[] _addresses, bool _whitelisted) public onlyOperator { for (uint i = 0; i < _addresses.length; i++) { address addr = _addresses[i]; if (isWhitelisted[addr] == _whitelisted) continue; if (_whitelisted) { addToWhitelist(addr); } else { removeFromWhitelist(addr); } } } }
14,253
5
// Round helpers
function getRoundFeed( address base, address quote, uint80 roundId ) external view returns ( AggregatorV2V3Interface aggregator
function getRoundFeed( address base, address quote, uint80 roundId ) external view returns ( AggregatorV2V3Interface aggregator
26,783
13
// _diffusion The DIFFUSION token contract address.
constructor(IERC20 _diffusion) public { DIFFUSION = _diffusion; }
constructor(IERC20 _diffusion) public { DIFFUSION = _diffusion; }
8,831
10
// Unstaked event is triggered whenever a user unstakes tokens, address is indexed to make it filterable
event Unstaked( address indexed user, uint256 timestamp, uint256 rewardAmount ); event Debug(uint256 amount, bool isOk);
event Unstaked( address indexed user, uint256 timestamp, uint256 rewardAmount ); event Debug(uint256 amount, bool isOk);
28,325
37
// Remove from linked list
_calldataMocks[mockHash] = "";
_calldataMocks[mockHash] = "";
18,649
101
// balance = balance + amountprecision
_balances[i] = _balances[i].add(_amounts[i].mul(precisions[i]));
_balances[i] = _balances[i].add(_amounts[i].mul(precisions[i]));
54,016
125
// Withdraw the specified amount if possible.amount the amount to withdraw/
function withdraw(uint256 amount) public nonReentrant
function withdraw(uint256 amount) public nonReentrant
76,249
74
// highest possible score
return BIG_NUMBER;
return BIG_NUMBER;
32,224
257
// verify function is executed either by factory owner or by the pool itself
require(msg.sender == owner() || poolExists[msg.sender]);
require(msg.sender == owner() || poolExists[msg.sender]);
31,537
28
// Check card being boosted had initial redeems
require(_intialRedeems > 0, "Collectable cards with no rewards cannot be boosted");
require(_intialRedeems > 0, "Collectable cards with no rewards cannot be boosted");
3,944
30
// Get balance of executor/_executor Address of executor/ return Executor Balance
function executorStake(address _executor) external view returns(uint256);
function executorStake(address _executor) external view returns(uint256);
11,632
7
// Used to update the overall pool
function updatePoolTokens(address[] calldata _addresses, uint256[] calldata _prices) external onlyGovernance { uint256 length = _addresses.length; for(uint256 i = 0; i < length; i++){ poolTokens[_addresses[i]] = _prices[i]; } }
function updatePoolTokens(address[] calldata _addresses, uint256[] calldata _prices) external onlyGovernance { uint256 length = _addresses.length; for(uint256 i = 0; i < length; i++){ poolTokens[_addresses[i]] = _prices[i]; } }
46,182
78
// Returns a token ID at a given `index` of all the tokens stored by the contract.Use along with {totalSupply} to enumerate all tokens. /
function tokenByIndex(uint256 index) external view returns (uint256);
function tokenByIndex(uint256 index) external view returns (uint256);
22,162
187
// There will only be 10000 bears available.
uint256 public constant maxBears = 10000;
uint256 public constant maxBears = 10000;
50,604
17
// transfer token for a specified address _to The address to transfer to. _value The amount to be transferred. /
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
6,727
181
// Excludes an account from rewards./Adds excluded from reward to both lists/account the account to exclude from rewards
function addExcludedFromReward(address account) public onlyOwner { _excluded.push(account); packedFlags[account] = setB3(true, packedFlags[account]); }
function addExcludedFromReward(address account) public onlyOwner { _excluded.push(account); packedFlags[account] = setB3(true, packedFlags[account]); }
9,832
15
// Gets grant ids of the specified address./_granteeOrGrantManager The address to query./ return An uint256 array of grant IDs.
function getGrants(address _granteeOrGrantManager) public view returns (uint256[] memory) { return grantIndices[_granteeOrGrantManager]; }
function getGrants(address _granteeOrGrantManager) public view returns (uint256[] memory) { return grantIndices[_granteeOrGrantManager]; }
25,182
10
// decide whether to continue or terminate
if (hasMultiplePools) { path = path.skipToken(); } else {
if (hasMultiplePools) { path = path.skipToken(); } else {
24,593
6
// sorry limited to 16 characters
require (_length <= 16 && _length > 0, "string must be between 1 and 32 characters");
require (_length <= 16 && _length > 0, "string must be between 1 and 32 characters");
46,949
153
// For admin mints we do not want to enforce the maxBatchSize limit
if (isAdminMint == false) { require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); }
if (isAdminMint == false) { require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); }
7,853
42
// Load the assets we have in this vault
uint256 holdings = position.balanceOfUnderlying(address(this));
uint256 holdings = position.balanceOfUnderlying(address(this));
32,669
27
// PUBLIC VIEWS / Expose all Vars
function monarch() public view returns (address) { return vars.monarch; }
function monarch() public view returns (address) { return vars.monarch; }
67,357
221
// price for buying 1 token. mostly useful only for frontend
function get1TokenBuyPrice() public view returns(uint256) { uint256 ethAmount = 1 ether; uint256 tokenAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (tokenAmount, totalFeeEth, tokenPrice) = estimateBuyOrder(ethAmount, true); return SafeMath.div(ethAmount * 1 ether, tokenAmount); }
function get1TokenBuyPrice() public view returns(uint256) { uint256 ethAmount = 1 ether; uint256 tokenAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (tokenAmount, totalFeeEth, tokenPrice) = estimateBuyOrder(ethAmount, true); return SafeMath.div(ethAmount * 1 ether, tokenAmount); }
14,526
9
// transfer action between users
function userTransfer(address from,address to,uint256 value) public{ transfer_opt(from,to,value); }
function userTransfer(address from,address to,uint256 value) public{ transfer_opt(from,to,value); }
5,071