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
60
// saved enough to pay debt, mint as usual rate
_savedForBoardroom = darkSupply.mul(_percentage).div(1e18);
_savedForBoardroom = darkSupply.mul(_percentage).div(1e18);
4,874
57
// Cancels the stream and transfers the tokens back on a pro rata basis. The stream and compounding stream vars objects get deleted to save gas and optimise contract storage. Throws if there is a token transfer failure. /
function cancelStreamInternal(uint256 streamId) internal { Types.Stream memory stream = streams[streamId]; uint256 senderBalance = balanceOf(streamId, stream.sender); uint256 recipientBalance = balanceOf(streamId, stream.recipient); delete streams[streamId]; IERC20 token = IERC20(stream.tokenAddress); if (recipientBalance > 0) require(token.transfer(stream.recipient, recipientBalance), "recipient token transfer failure"); if (senderBalance > 0) require(token.transfer(stream.sender, senderBalance), "sender token transfer failure"); emit CancelStream(streamId, stream.sender, stream.recipient, senderBalance, recipientBalance); }
function cancelStreamInternal(uint256 streamId) internal { Types.Stream memory stream = streams[streamId]; uint256 senderBalance = balanceOf(streamId, stream.sender); uint256 recipientBalance = balanceOf(streamId, stream.recipient); delete streams[streamId]; IERC20 token = IERC20(stream.tokenAddress); if (recipientBalance > 0) require(token.transfer(stream.recipient, recipientBalance), "recipient token transfer failure"); if (senderBalance > 0) require(token.transfer(stream.sender, senderBalance), "sender token transfer failure"); emit CancelStream(streamId, stream.sender, stream.recipient, senderBalance, recipientBalance); }
51,768
48
// calcSingleInGivenPoolOut tAi = tokenAmountIn(pS + pAo)\ /1\\pS = poolSupply || ---------| ^ | --------- ||bI - bI pAo = poolAmountOut\\pS/ \(wI / tW)bI = balanceIntAi =--------------------------------------------wI = weightIn/wI\tW = totalWeight|1 - ----| sF sF = swapFee (+ collectedFee)\tW/ /
{ uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint newPoolSupply = badd(poolSupply, poolAmountOut); uint poolRatio = bdiv(newPoolSupply, poolSupply); //uint newBalTi = poolRatio^(1/weightTi) * balTi; uint boo = bdiv(BConst.BONE, normalizedWeight); uint tokenInRatio = bpow(poolRatio, boo); uint newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn); uint tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn); // Do reverse order of fees charged in joinswap_ExternAmountIn, this way // ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ``` //uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ; uint zar = bmul(bsub(BConst.BONE, normalizedWeight), swapFee); tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BConst.BONE, zar)); return tokenAmountIn; }
{ uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint newPoolSupply = badd(poolSupply, poolAmountOut); uint poolRatio = bdiv(newPoolSupply, poolSupply); //uint newBalTi = poolRatio^(1/weightTi) * balTi; uint boo = bdiv(BConst.BONE, normalizedWeight); uint tokenInRatio = bpow(poolRatio, boo); uint newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn); uint tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn); // Do reverse order of fees charged in joinswap_ExternAmountIn, this way // ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ``` //uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ; uint zar = bmul(bsub(BConst.BONE, normalizedWeight), swapFee); tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BConst.BONE, zar)); return tokenAmountIn; }
22,272
2
// TraitFactory Wrapper Cliff Hall Side contract (not deployed or inherited) that extends`TraitFactory` and exposes methods for testing its internal functions. /
contract TraitFactoryWrapper is TraitFactory { /** * @notice Passthrough function for testing `TraitFactory.assembleArtwork`. * @param _generation the generation the Avastar belongs to * @param _traitHash the Avastar's trait hash * @return svg the fully rendered SVG for the Avastar */ function _assembleArtwork(Generation _generation, uint256 _traitHash) public view returns (string memory svg){ svg = assembleArtwork(_generation, _traitHash); } }
contract TraitFactoryWrapper is TraitFactory { /** * @notice Passthrough function for testing `TraitFactory.assembleArtwork`. * @param _generation the generation the Avastar belongs to * @param _traitHash the Avastar's trait hash * @return svg the fully rendered SVG for the Avastar */ function _assembleArtwork(Generation _generation, uint256 _traitHash) public view returns (string memory svg){ svg = assembleArtwork(_generation, _traitHash); } }
20,010
143
// Auction counter
uint256 public auctionCounter = 0;
uint256 public auctionCounter = 0;
15,759
8
// Moves `amount` tokens from `from` to `to` using theallowance mechanism. `amount` is then deducted from the caller'sallowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. /
function transferFrom(address from, address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
24,318
64
// return metadata, human readable name of the entity maintainer of this oracle Defined by the RCN RateOracle interface /
function maintainer() external view returns (string memory) { return imaintainer; }
function maintainer() external view returns (string memory) { return imaintainer; }
13,759
513
// If they don't have any debt ownership and they never minted, they don't have any fees. User ownership can reduce to 0 if user burns all synths, however they could have fees applicable for periods they had minted in before so we check debtEntryIndex.
if (debtEntryIndex == 0 && userOwnershipPercentage == 0) { uint[2][FEE_PERIOD_LENGTH] memory nullResults; return nullResults; }
if (debtEntryIndex == 0 && userOwnershipPercentage == 0) { uint[2][FEE_PERIOD_LENGTH] memory nullResults; return nullResults; }
29,495
170
// Mask to retrieve data for a given binData
uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1;
uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1;
34,266
4
// ERC20Interface(token).transferFrom(from, address(this), tokens);
require(requireFlag); LogTokenFallback(msg.sender, from, amount, data); return successFlag;
require(requireFlag); LogTokenFallback(msg.sender, from, amount, data); return successFlag;
48,916
218
// e^(+x), positive exponent or no exponent just shift left as many times as indicated by the exponent and the shift parameter
_magnitudeMult = _magnitudeMult.add(mintExp);
_magnitudeMult = _magnitudeMult.add(mintExp);
2,821
93
// Allows admin to set airdrop token for a given base tokenbaseToken Address of the base tokendestToken Address of the airdropped tokennumerator Numerator to calculate ratiodenominator Denominator to calculate ratiodate Date at which airdrop happened or will happen/
function setAirdrop( address baseToken, address destToken, uint256 numerator, uint256 denominator, uint256 date ) external onlyOwner
function setAirdrop( address baseToken, address destToken, uint256 numerator, uint256 denominator, uint256 date ) external onlyOwner
20,501
44
// Issues a refund to a given address. This function can only be called ifthe duration of the ICO has ended and the minimum goal has not been reached. _addr The address that will receive a refund. /
function getRefund(address _addr) public { if (_addr == 0x0) { _addr = msg.sender; } require(!isSuccess() && hasEnded() && investments[_addr] > 0); uint256 toRefund = investments[_addr]; investments[_addr] = 0; _addr.transfer(toRefund); RefundIssued(_addr, toRefund); }
function getRefund(address _addr) public { if (_addr == 0x0) { _addr = msg.sender; } require(!isSuccess() && hasEnded() && investments[_addr] > 0); uint256 toRefund = investments[_addr]; investments[_addr] = 0; _addr.transfer(toRefund); RefundIssued(_addr, toRefund); }
43,179
4
// ERC1820
function canImplementInterfaceForAddress( bytes32 interfaceHash, address addr ) external view returns(bytes32)
function canImplementInterfaceForAddress( bytes32 interfaceHash, address addr ) external view returns(bytes32)
32,463
39
// airlines[_name].balance,
airNamesList.length, airlines[_name].index, FlightSuretyData.isAirlineRegistered(_name), contractOwner ); return airlines[_name].isRegistered;
airNamesList.length, airlines[_name].index, FlightSuretyData.isAirlineRegistered(_name), contractOwner ); return airlines[_name].isRegistered;
23,024
41
// Redeem and substract from CETH Balance of user.
cETH[msg.sender] = cETH[msg.sender].sub(withdrawPortion);
cETH[msg.sender] = cETH[msg.sender].sub(withdrawPortion);
46,567
9
// send referral eggs
claimedEggs[referrals[msg.sender]]=SafeMath.add(claimedEggs[referrals[msg.sender]],SafeMath.div(eggsUsed,5));
claimedEggs[referrals[msg.sender]]=SafeMath.add(claimedEggs[referrals[msg.sender]],SafeMath.div(eggsUsed,5));
3,449
606
// Used for changing the Hegic fee recipient value New value /
function setHegicFeeRecipient(address value) external onlyOwner {
function setHegicFeeRecipient(address value) external onlyOwner {
38,453
338
// Calculate natural logarithm of x.Return NaN on negative x excluding -0.x quadruple precision numberreturn quadruple precision number /
function ln (bytes16 x) internal pure returns (bytes16) { return mul (log_2 (x), 0x3FFE62E42FEFA39EF35793C7673007E5); }
function ln (bytes16 x) internal pure returns (bytes16) { return mul (log_2 (x), 0x3FFE62E42FEFA39EF35793C7673007E5); }
20,132
259
// View function that, given an action type and arguments, will returnthe action ID or message hash that will need to be prefixed (according toEIP-191 0x45), hashed, and signed by both the user signing key and by thekey returned for this smart wallet by the Dharma Key Registry in order toconstruct a valid signature for a given generic atomic batch action. Anynonce value may be supplied, which enables constructing valid messagehashes for multiple future actions ahead of time. Finally, note that thisfunction must currently be implemented as a public function (instead of asan external one) due to an ABIEncoderV2 `UnimplementedFeatureError`. calls
function getGenericAtomicBatchActionID( Call[] memory calls, uint256 nonce, uint256 minimumActionGas
function getGenericAtomicBatchActionID( Call[] memory calls, uint256 nonce, uint256 minimumActionGas
9,825
110
// if a point is its own prefix (a galaxy) then don't register it
uint32 prefix = getPrefix(_point); if (prefix == _point) { return; }
uint32 prefix = getPrefix(_point); if (prefix == _point) { return; }
2,961
5
// Owner of this contract
address public owner;
address public owner;
32,415
266
// how much exactly to charge
payment = ethPerToken.mul(tokenAmount).div(1 ether);
payment = ethPerToken.mul(tokenAmount).div(1 ether);
43,231
95
// return Total number of unlocked distribution tokens. /
function totalUnlocked() public view returns (uint256) { return _unlockedPool.shareBalance(); }
function totalUnlocked() public view returns (uint256) { return _unlockedPool.shareBalance(); }
17,424
325
// RightsDao Lendroid Foundation DAO that handles NFTs, FRights, and IRights /
contract RightsDao is ChiWrapper, ERC721Holder { using Address for address; using SafeMath for uint256; int128 constant CONTRACT_TYPE_RIGHT_F = 1; int128 constant CONTRACT_TYPE_RIGHT_I = 2; // stores contract addresses of FRight and IRight mapping(int128 => address) public contracts; // stores addresses that have been whitelisted to perform freeze calls mapping(address => bool) public isWhitelisted; // stores whether freeze calls require caller to be whitelisted bool public whitelistedFreezeActivated = true; // stores latest current version of FRight mapping(int128 => uint256) public currentRightVersions; // return value for safeTransferFrom function calls of older ERC721 versions bytes4 constant ERC721_RECEIVED_OLD = 0xf0b9e5ba; constructor(address fRightContractAddress, address iRightContractAddress) public { require(fRightContractAddress.isContract(), "invalid fRightContractAddress"); require(iRightContractAddress.isContract(), "invalid iRightContractAddress"); contracts[CONTRACT_TYPE_RIGHT_F] = fRightContractAddress; contracts[CONTRACT_TYPE_RIGHT_I] = iRightContractAddress; currentRightVersions[CONTRACT_TYPE_RIGHT_F] = 1; currentRightVersions[CONTRACT_TYPE_RIGHT_I] = 1; } function onERC721Received(address, uint256, bytes memory) public pure returns (bytes4) { return ERC721_RECEIVED_OLD; } /** * @notice Internal function to record if freeze calls must be made only by whitelisted accounts * @dev set whitelistedFreezeActivated value as true or false * @param activate : bool indicating the toggle value */ function toggleWhitelistedFreeze(bool activate) external onlyOwner { if (activate) { require(!whitelistedFreezeActivated, "whitelisted freeze is already activated"); } else { require(whitelistedFreezeActivated, "whitelisted freeze is already deactivated"); } whitelistedFreezeActivated = activate; } /** * @notice Allows owner to add / remove given address to / from whitelist * @param addr : given address * @param status : bool indicating whitelist status of given address */ function toggleWhitelistStatus(address addr, bool status) external onlyOwner { require(addr != address(0), "invalid address"); isWhitelisted[addr] = status; } /** * @notice Allows owner to increment the current f version * @dev Increment currentFVersion by 1 */ function incrementCurrentRightVersion(int128 rightType) external onlyOwner { require((rightType == CONTRACT_TYPE_RIGHT_F) || (rightType == CONTRACT_TYPE_RIGHT_I), "invalid contract type"); currentRightVersions[rightType] = currentRightVersions[rightType].add(1); } /** * @notice Allows owner to set the base api url of F or I Right token * @dev Set base url of the server API representing the metadata of a Right Token * @param rightType type of Right contract * @param url API base url */ function setRightApiBaseUrl(int128 rightType, string calldata url) external onlyOwner { require((rightType == CONTRACT_TYPE_RIGHT_F) || (rightType == CONTRACT_TYPE_RIGHT_I), "invalid contract type"); if (rightType == CONTRACT_TYPE_RIGHT_F) { FRight(contracts[rightType]).setApiBaseUrl(url); } if (rightType == CONTRACT_TYPE_RIGHT_I) { IRight(contracts[rightType]).setApiBaseUrl(url); } } /** * @notice Freezes a given NFT Token * @dev Send the NFT to this contract, mint 1 FRight Token and 1 IRight Token * @param baseAssetAddress : address of the NFT * @param baseAssetId : id of the NFT * @param expiry : timestamp until which the NFT is locked in the dao * @param uint256Values : uint256 array [maxISupply, f_version, i_version] * @param stringValues : string array [purpose, description, imageUrl, termsUrl] */ function freeze(address baseAssetAddress, uint256 baseAssetId, uint256 expiry, uint256[3] calldata uint256Values, string[4] calldata stringValues) external discountCHI { if (whitelistedFreezeActivated) { require(isWhitelisted[msg.sender], "sender is not whitelisted"); } require(uint256Values[0] > 0, "invalid maximum I supply"); require(expiry > block.timestamp, "expiry should be in the future"); require((uint256Values[1] > 0) && (uint256Values[1] <= currentRightVersions[CONTRACT_TYPE_RIGHT_F]), "invalid f version"); require((uint256Values[2] > 0) && (uint256Values[2] <= currentRightVersions[CONTRACT_TYPE_RIGHT_I]), "invalid i version"); uint256 fRightId = FRight(contracts[CONTRACT_TYPE_RIGHT_F]).freeze([msg.sender, baseAssetAddress], [expiry, baseAssetId, uint256Values[0], uint256Values[1]]); // set exclusivity of IRights for the NFT bool isExclusive = uint256Values[0] == 1; IRight(contracts[CONTRACT_TYPE_RIGHT_I]).issue([msg.sender, baseAssetAddress], isExclusive, [fRightId, expiry, baseAssetId, uint256Values[2]], stringValues); ERC721(baseAssetAddress).safeTransferFrom(msg.sender, address(this), baseAssetId); } /** * @notice Unfreezes a given FRight. * @dev Burn the FRight token for a given token Id, and return the original NFT back to the caller * @param fRightId : id of the FRight token. */ function unfreeze(uint256 fRightId) external discountCHI { address fRightOwner = FRight(contracts[CONTRACT_TYPE_RIGHT_F]).ownerOf(fRightId); require(fRightOwner == msg.sender); (address baseAssetAddress, uint256 baseAssetId) = FRight(contracts[CONTRACT_TYPE_RIGHT_F]).baseAsset(fRightId); FRight(contracts[CONTRACT_TYPE_RIGHT_F]).unfreeze(fRightOwner, fRightId); ERC721(baseAssetAddress).transferFrom(address(this), msg.sender, baseAssetId); } /** * @notice Issues a IRight for a given FRight * @dev Check if IRight can be minted, Mint 1 IRight, Increment FRight.circulatingISupply by 1 * @param baseAssetAddress : address of base NFT asset * @param uint256Values : uint256 array [baseAssetId, fRightId, expiry, i_version] * @param stringValues : string array [purpose, description, imageUrl, termsUrl] */ function issueI(address baseAssetAddress, uint256[4] calldata uint256Values, string[4] calldata stringValues) external discountCHI { if (whitelistedFreezeActivated) { require(isWhitelisted[msg.sender], "sender is not whitelisted"); } require(uint256Values[2] > block.timestamp, "expiry should be in the future"); require((uint256Values[3] > 0) && (uint256Values[3] <= currentRightVersions[CONTRACT_TYPE_RIGHT_I]), "invalid i version"); if (uint256Values[1] > 0) { require(FRight(contracts[CONTRACT_TYPE_RIGHT_F]).isIMintable(uint256Values[1]), "cannot mint iRight"); require(msg.sender == FRight(contracts[CONTRACT_TYPE_RIGHT_F]).ownerOf(uint256Values[1]), "sender is not the owner of fRight"); uint256 fEndTime = FRight(contracts[CONTRACT_TYPE_RIGHT_F]).endTime(uint256Values[0]); require(uint256Values[1] <= fEndTime, "expiry cannot exceed fRight expiry"); (address fBaseAssetAddress, uint256 fBaseAssetId) = FRight(contracts[CONTRACT_TYPE_RIGHT_F]).baseAsset(uint256Values[1]); require(fBaseAssetAddress == baseAssetAddress); require(fBaseAssetId == uint256Values[0]); FRight(contracts[CONTRACT_TYPE_RIGHT_F]).incrementCirculatingISupply(uint256Values[1], 1); } else { require(msg.sender == ERC721(baseAssetAddress).ownerOf(uint256Values[0])); } IRight(contracts[CONTRACT_TYPE_RIGHT_I]).issue([msg.sender, baseAssetAddress], false, [uint256Values[1], uint256Values[2], uint256Values[0], uint256Values[3]], stringValues); } /** * @notice Revokes a given IRight. The IRight can be revoked at any time. * @dev Burn the IRight token. If the corresponding FRight exists, decrement its circulatingISupply by 1. * @param iRightId : id of the IRight token. */ function revokeI(uint256 iRightId) external discountCHI { address iRightOwner = IRight(contracts[CONTRACT_TYPE_RIGHT_I]).ownerOf(iRightId); require(msg.sender == iRightOwner, "sender is not the owner of iRight"); (address baseAssetAddress, uint256 baseAssetId) = IRight(contracts[CONTRACT_TYPE_RIGHT_I]).baseAsset(iRightId); bool isBaseAssetFrozen = FRight(contracts[CONTRACT_TYPE_RIGHT_F]).isFrozen(baseAssetAddress, baseAssetId); if (isBaseAssetFrozen) { uint256 fRightId = IRight(contracts[CONTRACT_TYPE_RIGHT_I]).parentId(iRightId); FRight(contracts[CONTRACT_TYPE_RIGHT_F]).decrementCirculatingISupply(fRightId, 1); } IRight(contracts[CONTRACT_TYPE_RIGHT_I]).revoke(iRightOwner, iRightId); } }
contract RightsDao is ChiWrapper, ERC721Holder { using Address for address; using SafeMath for uint256; int128 constant CONTRACT_TYPE_RIGHT_F = 1; int128 constant CONTRACT_TYPE_RIGHT_I = 2; // stores contract addresses of FRight and IRight mapping(int128 => address) public contracts; // stores addresses that have been whitelisted to perform freeze calls mapping(address => bool) public isWhitelisted; // stores whether freeze calls require caller to be whitelisted bool public whitelistedFreezeActivated = true; // stores latest current version of FRight mapping(int128 => uint256) public currentRightVersions; // return value for safeTransferFrom function calls of older ERC721 versions bytes4 constant ERC721_RECEIVED_OLD = 0xf0b9e5ba; constructor(address fRightContractAddress, address iRightContractAddress) public { require(fRightContractAddress.isContract(), "invalid fRightContractAddress"); require(iRightContractAddress.isContract(), "invalid iRightContractAddress"); contracts[CONTRACT_TYPE_RIGHT_F] = fRightContractAddress; contracts[CONTRACT_TYPE_RIGHT_I] = iRightContractAddress; currentRightVersions[CONTRACT_TYPE_RIGHT_F] = 1; currentRightVersions[CONTRACT_TYPE_RIGHT_I] = 1; } function onERC721Received(address, uint256, bytes memory) public pure returns (bytes4) { return ERC721_RECEIVED_OLD; } /** * @notice Internal function to record if freeze calls must be made only by whitelisted accounts * @dev set whitelistedFreezeActivated value as true or false * @param activate : bool indicating the toggle value */ function toggleWhitelistedFreeze(bool activate) external onlyOwner { if (activate) { require(!whitelistedFreezeActivated, "whitelisted freeze is already activated"); } else { require(whitelistedFreezeActivated, "whitelisted freeze is already deactivated"); } whitelistedFreezeActivated = activate; } /** * @notice Allows owner to add / remove given address to / from whitelist * @param addr : given address * @param status : bool indicating whitelist status of given address */ function toggleWhitelistStatus(address addr, bool status) external onlyOwner { require(addr != address(0), "invalid address"); isWhitelisted[addr] = status; } /** * @notice Allows owner to increment the current f version * @dev Increment currentFVersion by 1 */ function incrementCurrentRightVersion(int128 rightType) external onlyOwner { require((rightType == CONTRACT_TYPE_RIGHT_F) || (rightType == CONTRACT_TYPE_RIGHT_I), "invalid contract type"); currentRightVersions[rightType] = currentRightVersions[rightType].add(1); } /** * @notice Allows owner to set the base api url of F or I Right token * @dev Set base url of the server API representing the metadata of a Right Token * @param rightType type of Right contract * @param url API base url */ function setRightApiBaseUrl(int128 rightType, string calldata url) external onlyOwner { require((rightType == CONTRACT_TYPE_RIGHT_F) || (rightType == CONTRACT_TYPE_RIGHT_I), "invalid contract type"); if (rightType == CONTRACT_TYPE_RIGHT_F) { FRight(contracts[rightType]).setApiBaseUrl(url); } if (rightType == CONTRACT_TYPE_RIGHT_I) { IRight(contracts[rightType]).setApiBaseUrl(url); } } /** * @notice Freezes a given NFT Token * @dev Send the NFT to this contract, mint 1 FRight Token and 1 IRight Token * @param baseAssetAddress : address of the NFT * @param baseAssetId : id of the NFT * @param expiry : timestamp until which the NFT is locked in the dao * @param uint256Values : uint256 array [maxISupply, f_version, i_version] * @param stringValues : string array [purpose, description, imageUrl, termsUrl] */ function freeze(address baseAssetAddress, uint256 baseAssetId, uint256 expiry, uint256[3] calldata uint256Values, string[4] calldata stringValues) external discountCHI { if (whitelistedFreezeActivated) { require(isWhitelisted[msg.sender], "sender is not whitelisted"); } require(uint256Values[0] > 0, "invalid maximum I supply"); require(expiry > block.timestamp, "expiry should be in the future"); require((uint256Values[1] > 0) && (uint256Values[1] <= currentRightVersions[CONTRACT_TYPE_RIGHT_F]), "invalid f version"); require((uint256Values[2] > 0) && (uint256Values[2] <= currentRightVersions[CONTRACT_TYPE_RIGHT_I]), "invalid i version"); uint256 fRightId = FRight(contracts[CONTRACT_TYPE_RIGHT_F]).freeze([msg.sender, baseAssetAddress], [expiry, baseAssetId, uint256Values[0], uint256Values[1]]); // set exclusivity of IRights for the NFT bool isExclusive = uint256Values[0] == 1; IRight(contracts[CONTRACT_TYPE_RIGHT_I]).issue([msg.sender, baseAssetAddress], isExclusive, [fRightId, expiry, baseAssetId, uint256Values[2]], stringValues); ERC721(baseAssetAddress).safeTransferFrom(msg.sender, address(this), baseAssetId); } /** * @notice Unfreezes a given FRight. * @dev Burn the FRight token for a given token Id, and return the original NFT back to the caller * @param fRightId : id of the FRight token. */ function unfreeze(uint256 fRightId) external discountCHI { address fRightOwner = FRight(contracts[CONTRACT_TYPE_RIGHT_F]).ownerOf(fRightId); require(fRightOwner == msg.sender); (address baseAssetAddress, uint256 baseAssetId) = FRight(contracts[CONTRACT_TYPE_RIGHT_F]).baseAsset(fRightId); FRight(contracts[CONTRACT_TYPE_RIGHT_F]).unfreeze(fRightOwner, fRightId); ERC721(baseAssetAddress).transferFrom(address(this), msg.sender, baseAssetId); } /** * @notice Issues a IRight for a given FRight * @dev Check if IRight can be minted, Mint 1 IRight, Increment FRight.circulatingISupply by 1 * @param baseAssetAddress : address of base NFT asset * @param uint256Values : uint256 array [baseAssetId, fRightId, expiry, i_version] * @param stringValues : string array [purpose, description, imageUrl, termsUrl] */ function issueI(address baseAssetAddress, uint256[4] calldata uint256Values, string[4] calldata stringValues) external discountCHI { if (whitelistedFreezeActivated) { require(isWhitelisted[msg.sender], "sender is not whitelisted"); } require(uint256Values[2] > block.timestamp, "expiry should be in the future"); require((uint256Values[3] > 0) && (uint256Values[3] <= currentRightVersions[CONTRACT_TYPE_RIGHT_I]), "invalid i version"); if (uint256Values[1] > 0) { require(FRight(contracts[CONTRACT_TYPE_RIGHT_F]).isIMintable(uint256Values[1]), "cannot mint iRight"); require(msg.sender == FRight(contracts[CONTRACT_TYPE_RIGHT_F]).ownerOf(uint256Values[1]), "sender is not the owner of fRight"); uint256 fEndTime = FRight(contracts[CONTRACT_TYPE_RIGHT_F]).endTime(uint256Values[0]); require(uint256Values[1] <= fEndTime, "expiry cannot exceed fRight expiry"); (address fBaseAssetAddress, uint256 fBaseAssetId) = FRight(contracts[CONTRACT_TYPE_RIGHT_F]).baseAsset(uint256Values[1]); require(fBaseAssetAddress == baseAssetAddress); require(fBaseAssetId == uint256Values[0]); FRight(contracts[CONTRACT_TYPE_RIGHT_F]).incrementCirculatingISupply(uint256Values[1], 1); } else { require(msg.sender == ERC721(baseAssetAddress).ownerOf(uint256Values[0])); } IRight(contracts[CONTRACT_TYPE_RIGHT_I]).issue([msg.sender, baseAssetAddress], false, [uint256Values[1], uint256Values[2], uint256Values[0], uint256Values[3]], stringValues); } /** * @notice Revokes a given IRight. The IRight can be revoked at any time. * @dev Burn the IRight token. If the corresponding FRight exists, decrement its circulatingISupply by 1. * @param iRightId : id of the IRight token. */ function revokeI(uint256 iRightId) external discountCHI { address iRightOwner = IRight(contracts[CONTRACT_TYPE_RIGHT_I]).ownerOf(iRightId); require(msg.sender == iRightOwner, "sender is not the owner of iRight"); (address baseAssetAddress, uint256 baseAssetId) = IRight(contracts[CONTRACT_TYPE_RIGHT_I]).baseAsset(iRightId); bool isBaseAssetFrozen = FRight(contracts[CONTRACT_TYPE_RIGHT_F]).isFrozen(baseAssetAddress, baseAssetId); if (isBaseAssetFrozen) { uint256 fRightId = IRight(contracts[CONTRACT_TYPE_RIGHT_I]).parentId(iRightId); FRight(contracts[CONTRACT_TYPE_RIGHT_F]).decrementCirculatingISupply(fRightId, 1); } IRight(contracts[CONTRACT_TYPE_RIGHT_I]).revoke(iRightOwner, iRightId); } }
12,482
21
// Check validity of IPFS hash.Chech that IPFS hash begins with "Qm" and the length is 46. return isValid Result of validation./
function ipfsHashValidation(string memory ipfsHash) private pure returns (bool isValid)
function ipfsHashValidation(string memory ipfsHash) private pure returns (bool isValid)
22,032
234
// Set ETH price Can only be called by the owner _price ETH price /
function setEthPrice(uint256 _price) external onlyOwner { require(_price > 0, "PRICE_0"); ethPrice = _price; }
function setEthPrice(uint256 _price) external onlyOwner { require(_price > 0, "PRICE_0"); ethPrice = _price; }
53,488
11
// Check three of a kind
hand = [ int8(3), 16, 7, 42, 9]; (handVal, result) = poker.evaluateHand(hand); Assert.equal(int(handVal), int(PokerHandUtils.HandEnum.ThreeOfAKind), "Should be a three of a kind."); Assert.equal(result[0], int(3), "ThreeOfAKind Top should be a 3."); Assert.equal(result[1], int(9), "ThreeOfAKind Kicker should be a 9.");
hand = [ int8(3), 16, 7, 42, 9]; (handVal, result) = poker.evaluateHand(hand); Assert.equal(int(handVal), int(PokerHandUtils.HandEnum.ThreeOfAKind), "Should be a three of a kind."); Assert.equal(result[0], int(3), "ThreeOfAKind Top should be a 3."); Assert.equal(result[1], int(9), "ThreeOfAKind Kicker should be a 9.");
8,708
2
// Remove from whitelist /
function removeFromWhitelist(address[] calldata toRemoveAddresses) external onlyOwner { for (uint i = 0; i < toRemoveAddresses.length; i++) { delete whitelist[toRemoveAddresses[i]]; } }
function removeFromWhitelist(address[] calldata toRemoveAddresses) external onlyOwner { for (uint i = 0; i < toRemoveAddresses.length; i++) { delete whitelist[toRemoveAddresses[i]]; } }
3,859
77
// Same as {xref-Address-functionCall-address-bytes-string-}['functionCall'],but performing a static call. _Available since v3.3._ /
function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns(bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); }
function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns(bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); }
26,157
1
// Base URI
string private _baseURIextended; constructor( string memory _name, string memory _symbol
string private _baseURIextended; constructor( string memory _name, string memory _symbol
7,730
160
// Part of the Governor Bravo's interface: _"Gets the receipt for a voter on a given proposal"_. /
function getReceipt(uint256 proposalId, address voter) public view virtual returns (Receipt memory);
function getReceipt(uint256 proposalId, address voter) public view virtual returns (Receipt memory);
81,951
7
// Freeze contract: deny client deposits and node operations. /
function pause() external onlyRole(PAUSER_ROLE) { _pause(); }
function pause() external onlyRole(PAUSER_ROLE) { _pause(); }
15,363
4
// Changes the admin of a proxy. proxy Proxy to change admin. newAdmin Address to transfer proxy administration to. /
function changeProxyAdmin(AdminUpgradeabilityProxy proxy, address newAdmin) public onlyOwner { proxy.changeAdmin(newAdmin); }
function changeProxyAdmin(AdminUpgradeabilityProxy proxy, address newAdmin) public onlyOwner { proxy.changeAdmin(newAdmin); }
20,758
104
// Calculate Token /
function calculateAmount(uint256 amount) public view returns (uint256) { uint256 rate = getRate(); uint256 oneEther = 1 ether; uint256 rate_30perct = rate * 3 / 10; uint256 etherMul = muldiv(amount, rate_30perct).div(10e6); return etherMul; }
function calculateAmount(uint256 amount) public view returns (uint256) { uint256 rate = getRate(); uint256 oneEther = 1 ether; uint256 rate_30perct = rate * 3 / 10; uint256 etherMul = muldiv(amount, rate_30perct).div(10e6); return etherMul; }
61,288
5
// Create the contract, and sets the destination address to that of the creator /
function Forwarder(address pool) public { parentAddress = 0xE4402b9f8034A9B2857FFeE4Cf96605a364B16A1; }
function Forwarder(address pool) public { parentAddress = 0xE4402b9f8034A9B2857FFeE4Cf96605a364B16A1; }
44,445
5
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
case 0 { revert(0, returndatasize()) }
4,512
16
// ------------------------------------------------------------------------ -------------------------------------------------------------
function Venuscoins() public { symbol = "VNS"; name = "Venuscoins"; decimals = 8; _totalSupply = 1000000000000000; balances[ 0x6F30fF08237Cb9de03005c6CdE4182F12aCaaE10] = _totalSupply; Transfer(address(0), 0x6F30fF08237Cb9de03005c6CdE4182F12aCaaE10, _totalSupply); }
function Venuscoins() public { symbol = "VNS"; name = "Venuscoins"; decimals = 8; _totalSupply = 1000000000000000; balances[ 0x6F30fF08237Cb9de03005c6CdE4182F12aCaaE10] = _totalSupply; Transfer(address(0), 0x6F30fF08237Cb9de03005c6CdE4182F12aCaaE10, _totalSupply); }
25,990
0
// the cap enforced by this contract
uint256 public cap;
uint256 public cap;
34,487
8
// Store data at top of stack
uint256 tempData = stack[top];
uint256 tempData = stack[top];
18,934
7
// Flight data structure to be saved in data mapping
// struct Flight { // bool isRegistered; // FlightStatus status; // uint256 updatedTimestamp; // address airline; // }
// struct Flight { // bool isRegistered; // FlightStatus status; // uint256 updatedTimestamp; // address airline; // }
19,716
3
// By default withdraw MIM from bentoBox to this contract because they will need/ to get bridge from altchains to mainnet SpellStakingRewardDistributor./ On mainnet, this should be withdrawn to SpellStakingRewardDistributor directly.
address public mimWithdrawRecipient; bytes32 public bridgeRecipient; address public mimProvider; CauldronInfo[] public cauldronInfos; IBentoBoxV1[] public bentoBoxes;
address public mimWithdrawRecipient; bytes32 public bridgeRecipient; address public mimProvider; CauldronInfo[] public cauldronInfos; IBentoBoxV1[] public bentoBoxes;
40,153
83
// 1 week as a timestamp.
uint256 private oneWeek = 604800;
uint256 private oneWeek = 604800;
66,651
49
// Admin fee as a fraction of revenue.Smart contract doesn't use it, it's here just for storing purposes. newAdminFee fixed-point decimal in the same way as ether: 50% === 0.5 ether === "500000000000000000" /
function setAdminFee(uint newAdminFee) public onlyOwner { require(newAdminFee <= 1 ether, "error_adminFee"); adminFee = newAdminFee; emit AdminFeeChanged(adminFee); }
function setAdminFee(uint newAdminFee) public onlyOwner { require(newAdminFee <= 1 ether, "error_adminFee"); adminFee = newAdminFee; emit AdminFeeChanged(adminFee); }
36,831
69
// It's probably never going to happen, 4 billion tokens are A LOT, but let's just be 100% sure we never let this happen.
require(newCardId == uint(uint32(newCardId))); emit Birth(newCardId, _name, _owner); divCardIndexToPrice[newCardId] = _price;
require(newCardId == uint(uint32(newCardId))); emit Birth(newCardId, _name, _owner); divCardIndexToPrice[newCardId] = _price;
55,458
77
// Transfer token to the specified recipient
_transferGrToken(currentLock.beneficiary, currentLock.amount);
_transferGrToken(currentLock.beneficiary, currentLock.amount);
19,482
23
// Initiliazes the contract, like a constructor. function initialize( address _defaultAdmin, string memory _contractURI, address[] memory _trustedForwarders, address _saleRecipient, address _royaltyRecipient, uint128 _royaltyBps, uint128 _platformFeeBps, address _platformFeeRecipient
// ) external initializer { // // Initialize inherited contracts, most base-like -> most derived. // __ReentrancyGuard_init(); // __EIP712_init("TokenERC721", "1"); // __ERC2771Context_init(_trustedForwarders); // __ERC721_init("ABD Collectible", "ABD"); // __DefaultOperatorFilterer_init(); // // Initialize this contract's state. // _setOperatorRestriction(true); // royaltyRecipient = _royaltyRecipient; // royaltyBps = _royaltyBps; // platformFeeRecipient = _platformFeeRecipient; // primarySaleRecipient = _saleRecipient; // contractURI = _contractURI; // require(_platformFeeBps <= MAX_BPS, "exceeds MAX_BPS"); // platformFeeBps = _platformFeeBps; // _owner = _defaultAdmin; // _setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin); // _setupRole(MINTER_ROLE, _defaultAdmin); // _setupRole(TRANSFER_ROLE, _defaultAdmin); // _setupRole(TRANSFER_ROLE, address(0)); // }
// ) external initializer { // // Initialize inherited contracts, most base-like -> most derived. // __ReentrancyGuard_init(); // __EIP712_init("TokenERC721", "1"); // __ERC2771Context_init(_trustedForwarders); // __ERC721_init("ABD Collectible", "ABD"); // __DefaultOperatorFilterer_init(); // // Initialize this contract's state. // _setOperatorRestriction(true); // royaltyRecipient = _royaltyRecipient; // royaltyBps = _royaltyBps; // platformFeeRecipient = _platformFeeRecipient; // primarySaleRecipient = _saleRecipient; // contractURI = _contractURI; // require(_platformFeeBps <= MAX_BPS, "exceeds MAX_BPS"); // platformFeeBps = _platformFeeBps; // _owner = _defaultAdmin; // _setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin); // _setupRole(MINTER_ROLE, _defaultAdmin); // _setupRole(TRANSFER_ROLE, _defaultAdmin); // _setupRole(TRANSFER_ROLE, address(0)); // }
23,154
45
// Check interface ERC721Enumerable. /
function checkERC721EnumerableInterface( address _target ) internal
function checkERC721EnumerableInterface( address _target ) internal
4,331
61
// 3 000 000 can be issued from other currencies
uint public constant MAX_ISSUED_FROM_OTHER_CURRENCIES = 3000000 * 1 ether;
uint public constant MAX_ISSUED_FROM_OTHER_CURRENCIES = 3000000 * 1 ether;
39,807
24
// _blockNumber {uint256} return total supply {uint256}/
function totalSupplyAt(uint256 _blockNumber) public constant returns(uint256) {
function totalSupplyAt(uint256 _blockNumber) public constant returns(uint256) {
22,367
18
// 白虎
fees_[1] = RP1datasets.TeamFee(41,0); //41% to pot, 12% to aff, 2% to com, 1% to pot swap, 3% to air drop pot
fees_[1] = RP1datasets.TeamFee(41,0); //41% to pot, 12% to aff, 2% to com, 1% to pot swap, 3% to air drop pot
69,092
129
// Use along with {balanceOf} to enumerate all of ``owner``'s tokens./
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
50,433
25
// Returns the owner of the ERC1155 token contract. /
function owner() public view virtual override(Ownable, UpdatableOperatorFilterer) returns (address) { return Ownable.owner(); }
function owner() public view virtual override(Ownable, UpdatableOperatorFilterer) returns (address) { return Ownable.owner(); }
12,924
36
// Redeem liquidity liquidity Liquidity state tick Tick shares Sharesreturn Redemption index, Redemption target /
function redeem(Liquidity storage liquidity, uint128 tick, uint128 shares) internal returns (uint128, uint128) { Node storage node = liquidity.nodes[tick]; /* Redemption from inactive liquidity nodes is allowed to facilitate * restoring garbage collected nodes */ /* Snapshot redemption target */ uint128 redemptionIndex = node.redemptions.index; uint128 redemptionTarget = node.redemptions.pending; /* Add shares to pending redemptions */ node.redemptions.pending += shares; /* Initialize redemption record to save gas in loan callbacks */ if (node.redemptions.fulfilled[redemptionIndex].shares != type(uint128).max) { node.redemptions.fulfilled[redemptionIndex] = FulfilledRedemption({shares: type(uint128).max, amount: 0}); } /* Process any pending redemptions from available cash */ _processRedemptions(liquidity, node); return (redemptionIndex, redemptionTarget); }
function redeem(Liquidity storage liquidity, uint128 tick, uint128 shares) internal returns (uint128, uint128) { Node storage node = liquidity.nodes[tick]; /* Redemption from inactive liquidity nodes is allowed to facilitate * restoring garbage collected nodes */ /* Snapshot redemption target */ uint128 redemptionIndex = node.redemptions.index; uint128 redemptionTarget = node.redemptions.pending; /* Add shares to pending redemptions */ node.redemptions.pending += shares; /* Initialize redemption record to save gas in loan callbacks */ if (node.redemptions.fulfilled[redemptionIndex].shares != type(uint128).max) { node.redemptions.fulfilled[redemptionIndex] = FulfilledRedemption({shares: type(uint128).max, amount: 0}); } /* Process any pending redemptions from available cash */ _processRedemptions(liquidity, node); return (redemptionIndex, redemptionTarget); }
13,315
161
// Import issuer data from synthetixState.issuerData on FeePeriodClose() blockOnly callable by the contract owner, and only for 6 weeks after deployment. accounts Array of issuing addresses ratios Array of debt ratios periodToInsert The Fee Period to insert the historical records into feePeriodCloseIndex An accounts debtEntryIndex is valid when within the fee peroid,since the input ratio will be an average of the pervious periods it just needs to be> recentFeePeriods[periodToInsert].startingDebtIndex< recentFeePeriods[periodToInsert - 1].startingDebtIndex /
function importIssuerData( address[] calldata accounts, uint[] calldata ratios, uint periodToInsert, uint feePeriodCloseIndex
function importIssuerData( address[] calldata accounts, uint[] calldata ratios, uint periodToInsert, uint feePeriodCloseIndex
10,137
583
// Notify feePool to record sUSD to distribute as fees
feePool().recordFeePaid(amountInUSD); return true;
feePool().recordFeePaid(amountInUSD); return true;
29,526
1
// Sets transfer permissions on a specified address. _investor Address _sendAllowed Boolean, transfers from this address is allowed if true. _receiveAllowed Boolean, transfers to this address is allowed if true. /
function setPermission( address _investor, bool _sendAllowed, bool _receiveAllowed
function setPermission( address _investor, bool _sendAllowed, bool _receiveAllowed
23,525
218
// Return tokens to `getCaller()`.
_transferToCaller(redeem); _transferToCaller(optionAddress); emit Buy(getCaller(), optionAddress, quantity, premium); return (quantity, premium);
_transferToCaller(redeem); _transferToCaller(optionAddress); emit Buy(getCaller(), optionAddress, quantity, premium); return (quantity, premium);
64,428
140
// submits new claim of the policy book
function submitClaimAndInitializeVoting(string calldata evidenceURI) external;
function submitClaimAndInitializeVoting(string calldata evidenceURI) external;
45,253
147
// Maximum ConicPerTime uint256 public MAX_EMISSION_RATE = 0.5 ether; Initial ConicPerTime
uint256 public EMISSION_RATE = 0.0035 ether; 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); event SetFeeAddress(address indexed user, address indexed newAddress); event SetDevAddress(address indexed user, address indexed newAddress); event UpdateEmissionRate(address indexed user, uint256 conicPerSecond); event RewardLockedUp(address indexed user, uint256 indexed pid, uint256 amountLockedUp);
uint256 public EMISSION_RATE = 0.0035 ether; 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); event SetFeeAddress(address indexed user, address indexed newAddress); event SetDevAddress(address indexed user, address indexed newAddress); event UpdateEmissionRate(address indexed user, uint256 conicPerSecond); event RewardLockedUp(address indexed user, uint256 indexed pid, uint256 amountLockedUp);
33,844
58
// Item struct holds the templateId, a total of 4 additional features
struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; }
struct Item { uint256 templateId; // id of Template in the itemTemplates array uint8 feature1; uint8 feature2; uint8 feature3; uint8 feature4; uint8 equipmentPosition; bool burned; }
36,213
79
// Version of OpenZeppelin's BasicToken whose balances mapping has been replaced with a separate BalanceSheet contract. remove the need to copy over balances./ Basic token Basic version of StandardToken, with no allowances. /
contract ModularBasicToken is HasOwner { using SafeMath for uint256; event BalanceSheetSet(address indexed sheet); event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev claim ownership of the balancesheet contract * @param _sheet The address to of the balancesheet to claim. */ function setBalanceSheet(address _sheet) public onlyOwner returns (bool) { balances = BalanceSheet(_sheet); balances.claimOwnership(); emit BalanceSheetSet(_sheet); return true; } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { _transferAllArgs(msg.sender, _to, _value); return true; } function _transferAllArgs(address _from, address _to, uint256 _value) internal { // SafeMath.sub will throw if there is not enough balance. balances.subBalance(_from, _value); balances.addBalance(_to, _value); emit Transfer(_from, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances.balanceOf(_owner); } }
contract ModularBasicToken is HasOwner { using SafeMath for uint256; event BalanceSheetSet(address indexed sheet); event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev claim ownership of the balancesheet contract * @param _sheet The address to of the balancesheet to claim. */ function setBalanceSheet(address _sheet) public onlyOwner returns (bool) { balances = BalanceSheet(_sheet); balances.claimOwnership(); emit BalanceSheetSet(_sheet); return true; } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { _transferAllArgs(msg.sender, _to, _value); return true; } function _transferAllArgs(address _from, address _to, uint256 _value) internal { // SafeMath.sub will throw if there is not enough balance. balances.subBalance(_from, _value); balances.addBalance(_to, _value); emit Transfer(_from, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances.balanceOf(_owner); } }
54,065
22
// Verify trading limits for a trade in both directions. Reverts if the trading limits are met for outflow or inflow. exchangeId the ID of the exchange being used. _tokenIn the address of the token flowing in. amountIn the amount of token flowing in. _tokenOut the address of the token flowing out. amountOutthe amount of token flowing out. /
function guardTradingLimits( bytes32 exchangeId, address _tokenIn, uint256 amountIn, address _tokenOut, uint256 amountOut
function guardTradingLimits( bytes32 exchangeId, address _tokenIn, uint256 amountIn, address _tokenOut, uint256 amountOut
22,862
83
// Set the bank, which receive 95%ETH from tokens sale.newBank The address of new bank./
function setBank(address newBank) external validRecipient(newBank) onlyOwner() checkAccess()
function setBank(address newBank) external validRecipient(newBank) onlyOwner() checkAccess()
41,285
188
// Initializes the Strategy, this is called only once, when the contract is deployed. `_vault` should implement `VaultAPI`. _vault The address of the Vault responsible for this Strategy. /
constructor(address _vault) public { vault = VaultAPI(_vault); want = IERC20(vault.token()); want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = msg.sender; rewards = msg.sender; keeper = msg.sender; }
constructor(address _vault) public { vault = VaultAPI(_vault); want = IERC20(vault.token()); want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = msg.sender; rewards = msg.sender; keeper = msg.sender; }
51,926
2
// IVotingDefinitions IVotingDefinitions interface Cyril Lapinte - <[email protected]>SPDX-License-Identifier: MIT Error messages /
abstract contract IVotingDefinitions { address internal constant ANY_TARGET = address(bytes20("AnyTarget")); bytes4 internal constant ANY_METHOD = bytes4(bytes32("AnyMethod")); enum SessionState { UNDEFINED, PLANNED, CAMPAIGN, VOTING, EXECUTION, GRACE, CLOSED, ARCHIVED } enum ProposalState { UNDEFINED, DEFINED, CANCELLED, LOCKED, APPROVED, REJECTED, RESOLVED, CLOSED, ARCHIVED } // 4 digits precisions on percentage values uint256 internal constant PERCENT = 1000000; uint64 internal constant MIN_PERIOD_LENGTH = 200; // MAX_PERIOD_LENGTH (approx 10000 years) protects against period overflow uint64 internal constant MAX_PERIOD_LENGTH = 3652500 days; uint64 internal constant CAMPAIGN_PERIOD = 5 days; uint64 internal constant VOTING_PERIOD = 2 days; uint64 internal constant EXECUTION_PERIOD = 1 days; uint64 internal constant GRACE_PERIOD = 6 days; uint64 internal constant OFFSET_PERIOD = 2 days; // Proposal requirements in percent uint256 internal constant NEW_PROPOSAL_THRESHOLD = 1; uint256 internal constant DEFAULT_EXECUTION_THRESHOLD = 1; uint128 internal constant DEFAULT_MAJORITY = 500000; // 50% uint128 internal constant DEFAULT_QUORUM = 200000; // 20% uint8 internal constant OPEN_PROPOSALS = 5; uint8 internal constant MAX_PROPOSALS = 20; uint8 internal constant MAX_PROPOSALS_OPERATOR = 25; uint256 internal constant SESSION_RETENTION_PERIOD = 365 days; uint256 internal constant SESSION_RETENTION_COUNT = 10; }
abstract contract IVotingDefinitions { address internal constant ANY_TARGET = address(bytes20("AnyTarget")); bytes4 internal constant ANY_METHOD = bytes4(bytes32("AnyMethod")); enum SessionState { UNDEFINED, PLANNED, CAMPAIGN, VOTING, EXECUTION, GRACE, CLOSED, ARCHIVED } enum ProposalState { UNDEFINED, DEFINED, CANCELLED, LOCKED, APPROVED, REJECTED, RESOLVED, CLOSED, ARCHIVED } // 4 digits precisions on percentage values uint256 internal constant PERCENT = 1000000; uint64 internal constant MIN_PERIOD_LENGTH = 200; // MAX_PERIOD_LENGTH (approx 10000 years) protects against period overflow uint64 internal constant MAX_PERIOD_LENGTH = 3652500 days; uint64 internal constant CAMPAIGN_PERIOD = 5 days; uint64 internal constant VOTING_PERIOD = 2 days; uint64 internal constant EXECUTION_PERIOD = 1 days; uint64 internal constant GRACE_PERIOD = 6 days; uint64 internal constant OFFSET_PERIOD = 2 days; // Proposal requirements in percent uint256 internal constant NEW_PROPOSAL_THRESHOLD = 1; uint256 internal constant DEFAULT_EXECUTION_THRESHOLD = 1; uint128 internal constant DEFAULT_MAJORITY = 500000; // 50% uint128 internal constant DEFAULT_QUORUM = 200000; // 20% uint8 internal constant OPEN_PROPOSALS = 5; uint8 internal constant MAX_PROPOSALS = 20; uint8 internal constant MAX_PROPOSALS_OPERATOR = 25; uint256 internal constant SESSION_RETENTION_PERIOD = 365 days; uint256 internal constant SESSION_RETENTION_COUNT = 10; }
37,371
9
// adjust balance
balance[msg.sender] -= amount; return balance[msg.sender];
balance[msg.sender] -= amount; return balance[msg.sender];
50,522
21
// === Auditors
function addAuditor(address _auditor) external onlyOwner { require(auditors[_auditor].addr == address(0)); // Only add if they&#39;re not already added auditors[_auditor].banned = false; auditors[_auditor].addr = _auditor; auditors[_auditor].completedAudits = 0; auditors[_auditor].totalEarned = 0; emit AddedAuditor(_auditor); }
function addAuditor(address _auditor) external onlyOwner { require(auditors[_auditor].addr == address(0)); // Only add if they&#39;re not already added auditors[_auditor].banned = false; auditors[_auditor].addr = _auditor; auditors[_auditor].completedAudits = 0; auditors[_auditor].totalEarned = 0; emit AddedAuditor(_auditor); }
11,359
155
// memoize for gas optimization
uint256 oldAllowance = _allowance[sender][msg.sender];
uint256 oldAllowance = _allowance[sender][msg.sender];
14,098
81
// Sets {burnRate} to a value other than the initial one. /
function _setupBurnrate(uint8 burnrate_) internal virtual { _burnRate = burnrate_; }
function _setupBurnrate(uint8 burnrate_) internal virtual { _burnRate = burnrate_; }
161
1
// function createZombie(string memory _name, uint _dna) public {
function _createZombie(string memory _name, uint _dna) private {
function _createZombie(string memory _name, uint _dna) private {
6,282
52
// See withdrawNative _toAddress of the withdrawer _quantityAmount of the native ALOT to withdraw /
function withdrawNativePrivate(address _to, uint256 _quantity) private { safeDecrease(_to, native, _quantity, 0, Tx.ADDGAS); portfolioMinter.mint(_to, _quantity); }
function withdrawNativePrivate(address _to, uint256 _quantity) private { safeDecrease(_to, native, _quantity, 0, Tx.ADDGAS); portfolioMinter.mint(_to, _quantity); }
34,343
20
// The funding deadline. Investors are required to fund the principal before this exact point in time.
uint256 internal _fundingDeadline;
uint256 internal _fundingDeadline;
38,569
0
// Contract constructor. Sets metadata extension `name` and `symbol`. /
constructor() { nftName = "DTYTO"; nftSymbol = "TO"; }
constructor() { nftName = "DTYTO"; nftSymbol = "TO"; }
29,015
10
// Lending pool address
ILendingPool public lendingPool;
ILendingPool public lendingPool;
29,423
6
// make sure address is Player
// modifier isPlayer() { // require(msg.sender == _player, "Only Player can use this function."); // _; // }
// modifier isPlayer() { // require(msg.sender == _player, "Only Player can use this function."); // _; // }
13,956
58
// Emit when set new InsuranceAddress./_newInsuranceAddress the new InsuranceAddress.
event SetInsuranceAddress(address indexed _newInsuranceAddress);
event SetInsuranceAddress(address indexed _newInsuranceAddress);
31,953
76
// Update milestones of the project
typicalProjectMilestonesUpdate( _id, _nextStageStartTimestamp, _nextGateStartTimestamp, _nextSettledStartTimestamp, latestTaskDeadline );
typicalProjectMilestonesUpdate( _id, _nextStageStartTimestamp, _nextGateStartTimestamp, _nextSettledStartTimestamp, latestTaskDeadline );
16,017
1,053
// Encodes a misc data object into a bytes32 /
function encode(MiscData memory _data) private pure returns (bytes32 data) { data = data.setSwapFeePercentage(_data.swapFeePercentage); data = data.setOracleEnabled(_data.oracleEnabled); data = data.setOracleIndex(_data.oracleIndex); data = data.setOracleSampleCreationTimestamp(_data.oracleSampleCreationTimestamp); data = data.setLogTotalSupply(_data.logTotalSupply); data = data.setLogInvariant(_data.logInvariant); }
function encode(MiscData memory _data) private pure returns (bytes32 data) { data = data.setSwapFeePercentage(_data.swapFeePercentage); data = data.setOracleEnabled(_data.oracleEnabled); data = data.setOracleIndex(_data.oracleIndex); data = data.setOracleSampleCreationTimestamp(_data.oracleSampleCreationTimestamp); data = data.setLogTotalSupply(_data.logTotalSupply); data = data.setLogInvariant(_data.logInvariant); }
30,734
6
// URI HANDLING /
function setBaseURI(string memory customBaseURI_) external onlyOwner { customBaseURI = customBaseURI_; }
function setBaseURI(string memory customBaseURI_) external onlyOwner { customBaseURI = customBaseURI_; }
13,581
22
// Method for withdrawing proceeds from sales /
// function withdrawProceeds() external { // uint256 proceeds = s_proceeds[msg.sender]; // if (proceeds <= 0) { // revert NoProceeds(); // } // s_proceeds[msg.sender] = 0; // (bool success, ) = payable(msg.sender).call{value: proceeds}(""); // require(success, "Transfer failed"); // }
// function withdrawProceeds() external { // uint256 proceeds = s_proceeds[msg.sender]; // if (proceeds <= 0) { // revert NoProceeds(); // } // s_proceeds[msg.sender] = 0; // (bool success, ) = payable(msg.sender).call{value: proceeds}(""); // require(success, "Transfer failed"); // }
28,832
15
// Core SVG utilitiy library which helps us construct onchain SVG's with a simple, web-like API.
library svg { /* MAIN ELEMENTS */ function g(string memory _props, string memory _children) internal pure returns (string memory) { return el("g", _props, _children); } function path(string memory _props, string memory _children) internal pure returns (string memory) { return el("path", _props, _children); } function text(string memory _props, string memory _children) internal pure returns (string memory) { return el("text", _props, _children); } function line(string memory _props, string memory _children) internal pure returns (string memory) { return el("line", _props, _children); } function circle(string memory _props, string memory _children) internal pure returns (string memory) { return el("circle", _props, _children); } function rect(string memory _props, string memory _children) internal pure returns (string memory) { return el("rect", _props, _children); } function filter(string memory _props, string memory _children) internal pure returns (string memory) { return el("filter", _props, _children); } /* GRADIENTS */ function radialGradient(string memory _props, string memory _children) internal pure returns (string memory) { return el("radialGradient", _props, _children); } function linearGradient(string memory _props, string memory _children) internal pure returns (string memory) { return el("linearGradient", _props, _children); } function gradientStop( uint256 offset, string memory stopColor, string memory _props ) internal pure returns (string memory) { return el( "stop", string.concat( prop("stop-color", stopColor), " ", prop("offset", string.concat(utils.uint2str(offset), "%")), " ", _props ), utils.NULL ); } function animateTransform(string memory _props) internal pure returns (string memory) { return el("animateTransform", _props, utils.NULL); } /* COMMON */ // A generic element, can be used to construct any SVG (or HTML) element function el( string memory _tag, string memory _props, string memory _children ) internal pure returns (string memory) { return string.concat("<", _tag, " ", _props, ">", _children, "</", _tag, ">"); } // an SVG attribute function prop(string memory _key, string memory _val) internal pure returns (string memory) { return string.concat(_key, "=", '"', _val, '" '); } }
library svg { /* MAIN ELEMENTS */ function g(string memory _props, string memory _children) internal pure returns (string memory) { return el("g", _props, _children); } function path(string memory _props, string memory _children) internal pure returns (string memory) { return el("path", _props, _children); } function text(string memory _props, string memory _children) internal pure returns (string memory) { return el("text", _props, _children); } function line(string memory _props, string memory _children) internal pure returns (string memory) { return el("line", _props, _children); } function circle(string memory _props, string memory _children) internal pure returns (string memory) { return el("circle", _props, _children); } function rect(string memory _props, string memory _children) internal pure returns (string memory) { return el("rect", _props, _children); } function filter(string memory _props, string memory _children) internal pure returns (string memory) { return el("filter", _props, _children); } /* GRADIENTS */ function radialGradient(string memory _props, string memory _children) internal pure returns (string memory) { return el("radialGradient", _props, _children); } function linearGradient(string memory _props, string memory _children) internal pure returns (string memory) { return el("linearGradient", _props, _children); } function gradientStop( uint256 offset, string memory stopColor, string memory _props ) internal pure returns (string memory) { return el( "stop", string.concat( prop("stop-color", stopColor), " ", prop("offset", string.concat(utils.uint2str(offset), "%")), " ", _props ), utils.NULL ); } function animateTransform(string memory _props) internal pure returns (string memory) { return el("animateTransform", _props, utils.NULL); } /* COMMON */ // A generic element, can be used to construct any SVG (or HTML) element function el( string memory _tag, string memory _props, string memory _children ) internal pure returns (string memory) { return string.concat("<", _tag, " ", _props, ">", _children, "</", _tag, ">"); } // an SVG attribute function prop(string memory _key, string memory _val) internal pure returns (string memory) { return string.concat(_key, "=", '"', _val, '" '); } }
18,425
31
// /
function pauseClaims() public onlyOwner{ require(!claimsPaused,"claims already paused");claimsPaused = true;} function unpauseClaims() public onlyOwner{ require(claimsPaused,"claims not paused");claimsPaused = false;} modifier pauseable { require (!claimsPaused,"claimes are paused");_;} /** skeledrop enables an operator to allocate a free new mint claim to somebody from the crypt **/ // LISTS struct List { bytes32 root; uint256 remain; uint256 maxPer; }
function pauseClaims() public onlyOwner{ require(!claimsPaused,"claims already paused");claimsPaused = true;} function unpauseClaims() public onlyOwner{ require(claimsPaused,"claims not paused");claimsPaused = false;} modifier pauseable { require (!claimsPaused,"claimes are paused");_;} /** skeledrop enables an operator to allocate a free new mint claim to somebody from the crypt **/ // LISTS struct List { bytes32 root; uint256 remain; uint256 maxPer; }
12,770
14
// Address of the RequestAttestation precompiled contract. solhint-disable-next-line state-visibility
address constant REQUEST_ATTESTATION = address(0xff);
address constant REQUEST_ATTESTATION = address(0xff);
49,680
36
// Returns the whitelist mode of the specified spender address for the specified sponsor. sponsor The address of the sponsor to retrieve the whitelist mode for. spender The address of the spender to retrieve the whitelist mode for.return The whitelist mode of the specified spender address for the specified sponsor. /
function getSpenderWhitelistMode(address spender, address sponsor) public view returns (bool) { return sponsorApprovals[_getSpenderWhitelistKey(sponsor, spender)]; }
function getSpenderWhitelistMode(address spender, address sponsor) public view returns (bool) { return sponsorApprovals[_getSpenderWhitelistKey(sponsor, spender)]; }
33,425
2
// Converts a numeric string to it's unsigned integer representation./v The string to be converted.
function bytesToUInt(bytes32 v) constant returns (uint ret) { if (v == 0x0) { throw; } uint digit; for (uint i = 0; i < 32; i++) { digit = uint((uint(v) / (2 ** (8 * (31 - i)))) & 0xff); if (digit == 0) { break; } else if (digit < 48 || digit > 57) { throw; } ret *= 10; ret += (digit - 48); } return ret; }
function bytesToUInt(bytes32 v) constant returns (uint ret) { if (v == 0x0) { throw; } uint digit; for (uint i = 0; i < 32; i++) { digit = uint((uint(v) / (2 ** (8 * (31 - i)))) & 0xff); if (digit == 0) { break; } else if (digit < 48 || digit > 57) { throw; } ret *= 10; ret += (digit - 48); } return ret; }
50,503
18
// 给用户余额添加积分能量,只有存证成功后调用
event AddBalanced(address indexed operaAccount,address indexed to, uint256 value, bytes32 dataHash);
event AddBalanced(address indexed operaAccount,address indexed to, uint256 value, bytes32 dataHash);
34,034
88
// Validate oldOwner address and check that it corresponds to owner index.
require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "Invalid owner address provided"); require(owners[prevOwner] == oldOwner, "Invalid prevOwner, owner pair provided"); owners[newOwner] = owners[oldOwner]; owners[prevOwner] = newOwner; owners[oldOwner] = address(0); emit RemovedOwner(oldOwner); emit AddedOwner(newOwner);
require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "Invalid owner address provided"); require(owners[prevOwner] == oldOwner, "Invalid prevOwner, owner pair provided"); owners[newOwner] = owners[oldOwner]; owners[prevOwner] = newOwner; owners[oldOwner] = address(0); emit RemovedOwner(oldOwner); emit AddedOwner(newOwner);
40,889
188
// called in case crowdsale failed
function wcOnCrowdsaleFailure() internal;
function wcOnCrowdsaleFailure() internal;
23,902
15
// stage = Stages.networkIni;
owner=msg.sender;
owner=msg.sender;
22,311
14
// lottery storage
uint _lastLineId = 0; mapping(uint => Line) _lines; uint[] _linesIter; Line _tmpLine; // technical
uint _lastLineId = 0; mapping(uint => Line) _lines; uint[] _linesIter; Line _tmpLine; // technical
6,023
5
// Converts a cron string to a Spec, validates the spec, and encodes the spec.This should only be called off-chain, as it is gas expensive! cronString the cron string to convert and encodereturn the abi encoding of the Spec struct representing the cron string /
function encodeCronString(string memory cronString) external pure returns (bytes memory) { return CronExternal.toEncodedSpec(cronString); }
function encodeCronString(string memory cronString) external pure returns (bytes memory) { return CronExternal.toEncodedSpec(cronString); }
46,345
20
// Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. /
function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } }
function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } }
11,486
57
// 转token
function rescueToken(address _token, uint256 _amount) external onlyOwner { IERC20(_token).transfer(myWallet, _amount); }
function rescueToken(address _token, uint256 _amount) external onlyOwner { IERC20(_token).transfer(myWallet, _amount); }
39,725
208
// Get halving timestamp /
function getHalvingTimestamp() public view returns (uint256) { return halvingTimestamp; }
function getHalvingTimestamp() public view returns (uint256) { return halvingTimestamp; }
34,513
70
// CryptoPunks. Fix here for frontrun attack. Added in v1.0.2.
bytes memory punkIndexToAddress = abi.encodeWithSignature("punkIndexToAddress(uint256)", tokenId); (bool checkSuccess, bytes memory result) = address(assetAddr).staticcall(punkIndexToAddress); (address owner) = abi.decode(result, (address)); require(checkSuccess && owner == msg.sender, "Not the owner"); data = abi.encodeWithSignature("buyPunk(uint256)", tokenId);
bytes memory punkIndexToAddress = abi.encodeWithSignature("punkIndexToAddress(uint256)", tokenId); (bool checkSuccess, bytes memory result) = address(assetAddr).staticcall(punkIndexToAddress); (address owner) = abi.decode(result, (address)); require(checkSuccess && owner == msg.sender, "Not the owner"); data = abi.encodeWithSignature("buyPunk(uint256)", tokenId);
16,571
12
// Restakes all validator rewards/
function restake() external override whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) { uint256[] memory validators = validatorRegistry.getValidators(); for (uint256 idx = 0; idx < validators.length; idx++) { uint256 validatorId = validators[idx]; address validatorShare = stakeManager.getValidatorContract(validatorId); (uint256 amountRestaked, uint256 liquidReward) = restake(validatorShare); emit RestakeEvent(msg.sender, validatorId, amountRestaked, liquidReward); } }
function restake() external override whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) { uint256[] memory validators = validatorRegistry.getValidators(); for (uint256 idx = 0; idx < validators.length; idx++) { uint256 validatorId = validators[idx]; address validatorShare = stakeManager.getValidatorContract(validatorId); (uint256 amountRestaked, uint256 liquidReward) = restake(validatorShare); emit RestakeEvent(msg.sender, validatorId, amountRestaked, liquidReward); } }
82,483
2
// Update the Holograph Bridge module address bridge address of the Holograph Bridge smart contract to use /
function setBridge(address bridge) external;
function setBridge(address bridge) external;
21,589
67
// update winner reward and state
for (uint256 i=0; i<players[_round].length; i++) { if (players[_round][i].choice == theWinner) { players[_round][i].state = State.WIN; players[_round][i].balance = winAmount; addBalance(players[_round][i].addr, winAmount); totalReward = totalReward.sub(winAmount); } else {
for (uint256 i=0; i<players[_round].length; i++) { if (players[_round][i].choice == theWinner) { players[_round][i].state = State.WIN; players[_round][i].balance = winAmount; addBalance(players[_round][i].addr, winAmount); totalReward = totalReward.sub(winAmount); } else {
72,437
370
// Opium.Lib.Whitelisted contract implements whitelist with modifier to restrict access to only whitelisted addresses
contract Whitelisted { // Whitelist array address[] internal whitelist; /// @notice This modifier restricts access to functions, which could be called only by whitelisted addresses modifier onlyWhitelisted() { // Allowance flag bool allowed = false; // Going through whitelisted addresses array uint256 whitelistLength = whitelist.length; for (uint256 i = 0; i < whitelistLength; i++) { // If `msg.sender` is met within whitelisted addresses, raise the flag and exit the loop if (whitelist[i] == msg.sender) { allowed = true; break; } } // Check if flag was raised require(allowed, "Only whitelisted allowed"); _; } /// @notice Getter for whitelisted addresses array /// @return Array of whitelisted addresses function getWhitelist() public view returns (address[] memory) { return whitelist; } }
contract Whitelisted { // Whitelist array address[] internal whitelist; /// @notice This modifier restricts access to functions, which could be called only by whitelisted addresses modifier onlyWhitelisted() { // Allowance flag bool allowed = false; // Going through whitelisted addresses array uint256 whitelistLength = whitelist.length; for (uint256 i = 0; i < whitelistLength; i++) { // If `msg.sender` is met within whitelisted addresses, raise the flag and exit the loop if (whitelist[i] == msg.sender) { allowed = true; break; } } // Check if flag was raised require(allowed, "Only whitelisted allowed"); _; } /// @notice Getter for whitelisted addresses array /// @return Array of whitelisted addresses function getWhitelist() public view returns (address[] memory) { return whitelist; } }
47,102