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
39
// we are somewhere in the middle, we need to find the right spot first...
uint buyPrice = tokens[tokenIndex].curBuyPrice; bool weFoundIt = false; while (buyPrice > 0 && !weFoundIt) { if ( buyPrice < priceInWei && tokens[tokenIndex].buyBook[buyPrice].higherPrice > priceInWei ) {
uint buyPrice = tokens[tokenIndex].curBuyPrice; bool weFoundIt = false; while (buyPrice > 0 && !weFoundIt) { if ( buyPrice < priceInWei && tokens[tokenIndex].buyBook[buyPrice].higherPrice > priceInWei ) {
23,072
4
// Provides validation for callbacks from PancakeSwap V3 Pools
library CallbackValidation { /// @notice Returns the address of a valid PancakeSwap V3 Pool /// @param deployer The contract address of the PancakeSwap V3 Deployer /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The V3 pool contract address function verifyCallback( address deployer, address tokenA, address tokenB, uint24 fee ) internal view returns (IPancakeV3Pool pool) { return verifyCallback(deployer, PoolAddress.getPoolKey(tokenA, tokenB, fee)); } /// @notice Returns the address of a valid PancakeSwap V3 Pool /// @param deployer The contract address of the PancakeSwap V3 deployer /// @param poolKey The identifying key of the V3 pool /// @return pool The V3 pool contract address function verifyCallback(address deployer, PoolAddress.PoolKey memory poolKey) internal view returns (IPancakeV3Pool pool) { pool = IPancakeV3Pool(PoolAddress.computeAddress(deployer, poolKey)); require(msg.sender == address(pool)); } }
library CallbackValidation { /// @notice Returns the address of a valid PancakeSwap V3 Pool /// @param deployer The contract address of the PancakeSwap V3 Deployer /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The V3 pool contract address function verifyCallback( address deployer, address tokenA, address tokenB, uint24 fee ) internal view returns (IPancakeV3Pool pool) { return verifyCallback(deployer, PoolAddress.getPoolKey(tokenA, tokenB, fee)); } /// @notice Returns the address of a valid PancakeSwap V3 Pool /// @param deployer The contract address of the PancakeSwap V3 deployer /// @param poolKey The identifying key of the V3 pool /// @return pool The V3 pool contract address function verifyCallback(address deployer, PoolAddress.PoolKey memory poolKey) internal view returns (IPancakeV3Pool pool) { pool = IPancakeV3Pool(PoolAddress.computeAddress(deployer, poolKey)); require(msg.sender == address(pool)); } }
17,348
94
// Creates `amount` tokens and assigns them to `account`, increasingthe total supply. Only 90000 UDONS for Pre=Sale! /
function _premint(address account) internal virtual { require(now <= endDate && _totalSupply == 0); _beforeTokenTransfer(address(0), account, hardcap); _totalSupply = _totalSupply.add(hardcap); _balances[account] = _balances[account].add(hardcap); emit Transfer(address(0), account, hardcap); }
function _premint(address account) internal virtual { require(now <= endDate && _totalSupply == 0); _beforeTokenTransfer(address(0), account, hardcap); _totalSupply = _totalSupply.add(hardcap); _balances[account] = _balances[account].add(hardcap); emit Transfer(address(0), account, hardcap); }
1,982
92
// Interface definition for the ButtonToken ERC20 wrapper contract
interface IButtonToken is IButtonWrapper, IRebasingERC20 { /// @dev The reference to the oracle which feeds in the /// price of the underlying token. function oracle() external view returns (address); /// @dev Most recent price recorded from the oracle. function lastPrice() external view returns (uint256); /// @dev Update reference to the oracle contract and resets price. /// @param oracle_ The address of the new oracle. function updateOracle(address oracle_) external; /// @dev Log to record changes to the oracle. /// @param oracle The address of the new oracle. event OracleUpdated(address oracle); /// @dev Contract initializer function initialize( address underlying_, string memory name_, string memory symbol_, address oracle_ ) external; }
interface IButtonToken is IButtonWrapper, IRebasingERC20 { /// @dev The reference to the oracle which feeds in the /// price of the underlying token. function oracle() external view returns (address); /// @dev Most recent price recorded from the oracle. function lastPrice() external view returns (uint256); /// @dev Update reference to the oracle contract and resets price. /// @param oracle_ The address of the new oracle. function updateOracle(address oracle_) external; /// @dev Log to record changes to the oracle. /// @param oracle The address of the new oracle. event OracleUpdated(address oracle); /// @dev Contract initializer function initialize( address underlying_, string memory name_, string memory symbol_, address oracle_ ) external; }
18,362
3
// Encode int self The int to encodereturn The RLP encoded int in bytes /
function encodeInt(int self) internal pure returns (bytes memory) { return encodeUint(uint(self)); }
function encodeInt(int self) internal pure returns (bytes memory) { return encodeUint(uint(self)); }
47,266
53
// Convert to string and append 's' to represent seconds in the SVG.
string memory animationDuration = string.concat(random.toString(), "s");
string memory animationDuration = string.concat(random.toString(), "s");
35,636
4
// Invite users to the event
for (uint i = 0; i < invitees.length; i++) { eventInvitations[eventID].push(invitees[i]); // push invitees to struct emit UserInvited(eventID, title, invitees[i]); }
for (uint i = 0; i < invitees.length; i++) { eventInvitations[eventID].push(invitees[i]); // push invitees to struct emit UserInvited(eventID, title, invitees[i]); }
34,271
296
// If there's a non-0x00 after an 0x00, this is not a valid string.
else if (seen0x00) { revert("setUsername error: invalid string; character present after null terminator"); }
else if (seen0x00) { revert("setUsername error: invalid string; character present after null terminator"); }
38,738
189
// File: EarlyMintIncentive.sol Allows the contract to have the first x tokens have a discount or zero fee that can be calculated on the fly.
abstract contract EarlyMintIncentive is Teams, ERC721A { uint256 public PRICE = 0.004 ether; uint256 public EARLY_MINT_PRICE = 0 ether; uint256 public earlyMintTokenIdCap = 1000; bool public usingEarlyMintIncentive = true; function enableEarlyMintIncentive() public onlyTeamOrOwner { usingEarlyMintIncentive = true; } function disableEarlyMintIncentive() public onlyTeamOrOwner { usingEarlyMintIncentive = false; } /** * @dev Set the max token ID in which the cost incentive will be applied. * @param _newTokenIdCap max tokenId in which incentive will be applied */ function setEarlyMintTokenIdCap(uint256 _newTokenIdCap) public onlyTeamOrOwner { require(_newTokenIdCap <= collectionSize, "Cannot set incentive tokenId cap larger than totaly supply."); require(_newTokenIdCap >= 1, "Cannot set tokenId cap to less than the first token"); earlyMintTokenIdCap = _newTokenIdCap; } /** * @dev Set the incentive mint price * @param _feeInWei new price per token when in incentive range */ function setEarlyIncentivePrice(uint256 _feeInWei) public onlyTeamOrOwner { EARLY_MINT_PRICE = _feeInWei; } /** * @dev Set the primary mint price - the base price when not under incentive * @param _feeInWei new price per token */ function setPrice(uint256 _feeInWei) public onlyTeamOrOwner { PRICE = _feeInWei; } function getPrice(uint256 _count) public view returns (uint256) { require(_count > 0, "Must be minting at least 1 token."); // short circuit function if we dont need to even calc incentive pricing // short circuit if the current tokenId is also already over cap if( usingEarlyMintIncentive == false || currentTokenId() > earlyMintTokenIdCap ) { return PRICE * _count; } uint256 endingTokenId = currentTokenId() + _count; // If qty to mint results in a final token ID less than or equal to the cap then // the entire qty is within free mint. if(endingTokenId <= earlyMintTokenIdCap) { return EARLY_MINT_PRICE * _count; } // If the current token id is less than the incentive cap // and the ending token ID is greater than the incentive cap // we will be straddling the cap so there will be some amount // that are incentive and some that are regular fee. uint256 incentiveTokenCount = earlyMintTokenIdCap - currentTokenId(); uint256 outsideIncentiveCount = endingTokenId - earlyMintTokenIdCap; return (EARLY_MINT_PRICE * incentiveTokenCount) + (PRICE * outsideIncentiveCount); } }
abstract contract EarlyMintIncentive is Teams, ERC721A { uint256 public PRICE = 0.004 ether; uint256 public EARLY_MINT_PRICE = 0 ether; uint256 public earlyMintTokenIdCap = 1000; bool public usingEarlyMintIncentive = true; function enableEarlyMintIncentive() public onlyTeamOrOwner { usingEarlyMintIncentive = true; } function disableEarlyMintIncentive() public onlyTeamOrOwner { usingEarlyMintIncentive = false; } /** * @dev Set the max token ID in which the cost incentive will be applied. * @param _newTokenIdCap max tokenId in which incentive will be applied */ function setEarlyMintTokenIdCap(uint256 _newTokenIdCap) public onlyTeamOrOwner { require(_newTokenIdCap <= collectionSize, "Cannot set incentive tokenId cap larger than totaly supply."); require(_newTokenIdCap >= 1, "Cannot set tokenId cap to less than the first token"); earlyMintTokenIdCap = _newTokenIdCap; } /** * @dev Set the incentive mint price * @param _feeInWei new price per token when in incentive range */ function setEarlyIncentivePrice(uint256 _feeInWei) public onlyTeamOrOwner { EARLY_MINT_PRICE = _feeInWei; } /** * @dev Set the primary mint price - the base price when not under incentive * @param _feeInWei new price per token */ function setPrice(uint256 _feeInWei) public onlyTeamOrOwner { PRICE = _feeInWei; } function getPrice(uint256 _count) public view returns (uint256) { require(_count > 0, "Must be minting at least 1 token."); // short circuit function if we dont need to even calc incentive pricing // short circuit if the current tokenId is also already over cap if( usingEarlyMintIncentive == false || currentTokenId() > earlyMintTokenIdCap ) { return PRICE * _count; } uint256 endingTokenId = currentTokenId() + _count; // If qty to mint results in a final token ID less than or equal to the cap then // the entire qty is within free mint. if(endingTokenId <= earlyMintTokenIdCap) { return EARLY_MINT_PRICE * _count; } // If the current token id is less than the incentive cap // and the ending token ID is greater than the incentive cap // we will be straddling the cap so there will be some amount // that are incentive and some that are regular fee. uint256 incentiveTokenCount = earlyMintTokenIdCap - currentTokenId(); uint256 outsideIncentiveCount = endingTokenId - earlyMintTokenIdCap; return (EARLY_MINT_PRICE * incentiveTokenCount) + (PRICE * outsideIncentiveCount); } }
31,959
5
// Mapping of strikes for each epoch
mapping(uint256 => uint256[]) public epochStrikes;
mapping(uint256 => uint256[]) public epochStrikes;
50,506
0
// with some slight modifications for gas optimization (merkle root of ParaHeads, adding Option<H256> pub key root):
* MMRLeaf { * H256 (Polkadot block header hash) * H256 (root of merkle tree of `ParaHead`s) * H256 (root of merkle tree of BridgeMessage) * Option<H256> (merkle root of a tree of new validator pubkey) * }
* MMRLeaf { * H256 (Polkadot block header hash) * H256 (root of merkle tree of `ParaHead`s) * H256 (root of merkle tree of BridgeMessage) * Option<H256> (merkle root of a tree of new validator pubkey) * }
46,181
307
// returns closeBorrowAmount_TargetUnderwaterAsset(1+liquidationDiscount)priceBorrow/priceCollateral/
function calculateAmountSeize(Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint closeBorrowAmount_TargetUnderwaterAsset) internal view returns (Error, uint) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp(Exp({mantissa: mantissaOne}), liquidationDiscount); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp(underwaterAssetPrice, liquidationMultiplier); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar(priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); }
function calculateAmountSeize(Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint closeBorrowAmount_TargetUnderwaterAsset) internal view returns (Error, uint) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp(Exp({mantissa: mantissaOne}), liquidationDiscount); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp(underwaterAssetPrice, liquidationMultiplier); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar(priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); }
37,761
151
// Waifu Token with Governance.
contract Waifu is BEP20("WAIFU", "WAIFU") { // Burn address address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; address public MARKETING_ADDRESS1; mapping (address => bool) public _isExcludedFromFee; uint256 public marketingFee1 = 0; uint256 public burnFee = 5; constructor() public { MARKETING_ADDRESS1 = 0xDfA4EC7F13450B86eFAE75F5286F0e66a02e6C2B; _mint(0x88849242b4cA6eb0E4540E92fd680Ca92f6c4c73,100000000000000000000000000); excludeFromFee(MARKETING_ADDRESS1); excludeFromFee(0x88849242b4cA6eb0E4540E92fd680Ca92f6c4c73); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function changeMarketingAddress(address _marketing) public { require(msg.sender == MARKETING_ADDRESS1, "not owner"); MARKETING_ADDRESS1 = _marketing; } function excludeFromFee(address account) public { require(msg.sender == MARKETING_ADDRESS1 || msg.sender == owner(), "not owner"); _isExcludedFromFee[account] = true; } function includeInFee(address account) public { require(msg.sender == MARKETING_ADDRESS1 || msg.sender == owner(), "not owner"); _isExcludedFromFee[account] = false; } // function changeMarketingFee(uint256 _fee) public { // require(msg.sender == MARKETING_ADDRESS1 || msg.sender == MARKETING_ADDRESS2 || msg.sender == MARKETING_ADDRESS3, "now owner"); // marketingFee = _fee; // } function chageMarketingFee1(uint256 _fee)public { require(burnFee.add(_fee) <= 15, "fee too high"); require(msg.sender == MARKETING_ADDRESS1 || msg.sender == owner(), "not owner of fee"); marketingFee1 = _fee; } function changeBurnFee(uint256 _fee)public { require(marketingFee1.add(_fee) <= 15, "fee too high"); require(msg.sender == MARKETING_ADDRESS1 || msg.sender == owner(), "not owner of fee"); marketingFee1 = _fee; } bool public feeOn = true; /// @dev overrides transfer function to meet tokenomics of Waifu function _transfer(address sender, address recipient, uint256 amount) internal virtual override { if (recipient == BURN_ADDRESS || feeOn == false || _isExcludedFromFee[recipient] || _isExcludedFromFee[sender]) { super._transfer(sender, recipient, amount); } else { // percentage of fee uint256 marketingAmount1 = amount.mul(marketingFee1).div(100); uint256 burnAmount = amount.mul(burnFee).div(100); uint256 totalFee = marketingAmount1.add(burnAmount); // transfer rest of % to recipient uint256 sendAmount = amount.sub(totalFee); super._transfer(sender, MARKETING_ADDRESS1, marketingAmount1); super._transfer(sender, BURN_ADDRESS, burnAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; emit Transfer(sender, recipient, sendAmount); } } // change fee function changeFeeStatus() public { require(msg.sender == MARKETING_ADDRESS1 || msg.sender == owner(), "not owner"); feeOn = !feeOn; } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "PERA::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "PERA::delegateBySig: invalid nonce"); require(now <= expiry, "PERA::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "PERA::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying Waifu (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "PERA::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract Waifu is BEP20("WAIFU", "WAIFU") { // Burn address address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; address public MARKETING_ADDRESS1; mapping (address => bool) public _isExcludedFromFee; uint256 public marketingFee1 = 0; uint256 public burnFee = 5; constructor() public { MARKETING_ADDRESS1 = 0xDfA4EC7F13450B86eFAE75F5286F0e66a02e6C2B; _mint(0x88849242b4cA6eb0E4540E92fd680Ca92f6c4c73,100000000000000000000000000); excludeFromFee(MARKETING_ADDRESS1); excludeFromFee(0x88849242b4cA6eb0E4540E92fd680Ca92f6c4c73); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function changeMarketingAddress(address _marketing) public { require(msg.sender == MARKETING_ADDRESS1, "not owner"); MARKETING_ADDRESS1 = _marketing; } function excludeFromFee(address account) public { require(msg.sender == MARKETING_ADDRESS1 || msg.sender == owner(), "not owner"); _isExcludedFromFee[account] = true; } function includeInFee(address account) public { require(msg.sender == MARKETING_ADDRESS1 || msg.sender == owner(), "not owner"); _isExcludedFromFee[account] = false; } // function changeMarketingFee(uint256 _fee) public { // require(msg.sender == MARKETING_ADDRESS1 || msg.sender == MARKETING_ADDRESS2 || msg.sender == MARKETING_ADDRESS3, "now owner"); // marketingFee = _fee; // } function chageMarketingFee1(uint256 _fee)public { require(burnFee.add(_fee) <= 15, "fee too high"); require(msg.sender == MARKETING_ADDRESS1 || msg.sender == owner(), "not owner of fee"); marketingFee1 = _fee; } function changeBurnFee(uint256 _fee)public { require(marketingFee1.add(_fee) <= 15, "fee too high"); require(msg.sender == MARKETING_ADDRESS1 || msg.sender == owner(), "not owner of fee"); marketingFee1 = _fee; } bool public feeOn = true; /// @dev overrides transfer function to meet tokenomics of Waifu function _transfer(address sender, address recipient, uint256 amount) internal virtual override { if (recipient == BURN_ADDRESS || feeOn == false || _isExcludedFromFee[recipient] || _isExcludedFromFee[sender]) { super._transfer(sender, recipient, amount); } else { // percentage of fee uint256 marketingAmount1 = amount.mul(marketingFee1).div(100); uint256 burnAmount = amount.mul(burnFee).div(100); uint256 totalFee = marketingAmount1.add(burnAmount); // transfer rest of % to recipient uint256 sendAmount = amount.sub(totalFee); super._transfer(sender, MARKETING_ADDRESS1, marketingAmount1); super._transfer(sender, BURN_ADDRESS, burnAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; emit Transfer(sender, recipient, sendAmount); } } // change fee function changeFeeStatus() public { require(msg.sender == MARKETING_ADDRESS1 || msg.sender == owner(), "not owner"); feeOn = !feeOn; } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "PERA::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "PERA::delegateBySig: invalid nonce"); require(now <= expiry, "PERA::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "PERA::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying Waifu (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "PERA::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
10,667
0
// Retorna verdadeiro ou falso para comparacao de duas strings _strA primeira string para comparacao _strB segunda string para comparacao Copiei este codigo de um github qualquer, de tanta raiva que fiquei tentandonao precisar disso. :-(return true se as strings forem consideradas iguais e false se forem diferentes /
function equal(string memory _strA, string memory _strB) public pure returns (bool) { return compare(_strA, _strB) == 0; }
function equal(string memory _strA, string memory _strB) public pure returns (bool) { return compare(_strA, _strB) == 0; }
49,209
81
// Multiplies two numbers, throws on overflow./
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; }
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; }
3,076
105
// ======== INTERNAL HELPER FUNCTIONS ======== //allow user to stake payout automatically_stake bool_amount uint return uint /
function stakeOrSend( address _recipient, bool _stake, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake Time.transfer( _recipient, _amount ); // send payout } else { // if user wants to stake if ( useHelper ) { // use if staking warmup is 0 Time.approve( address(stakingHelper), _amount ); stakingHelper.stake( _amount, _recipient ); } else { Time.approve( address(staking), _amount ); staking.stake( _amount, _recipient ); } } return _amount; }
function stakeOrSend( address _recipient, bool _stake, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake Time.transfer( _recipient, _amount ); // send payout } else { // if user wants to stake if ( useHelper ) { // use if staking warmup is 0 Time.approve( address(stakingHelper), _amount ); stakingHelper.stake( _amount, _recipient ); } else { Time.approve( address(staking), _amount ); staking.stake( _amount, _recipient ); } } return _amount; }
29,306
32
// Set a previously open channel as closed via "swap & pop" method. Decrement located index to get the index of the closed channel.
uint256 removedChannelIndex;
uint256 removedChannelIndex;
15,915
66
// Update fee address by the previous fee address.
function setFeeAddress(address _feeAddress) public { require(_feeAddress != address(0), "setFeeAddress: invalid address"); require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN"); feeAddress = _feeAddress; emit SetFeeAddress(msg.sender, _feeAddress); }
function setFeeAddress(address _feeAddress) public { require(_feeAddress != address(0), "setFeeAddress: invalid address"); require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN"); feeAddress = _feeAddress; emit SetFeeAddress(msg.sender, _feeAddress); }
8,693
115
// encode 64 bits of rate (decimal = 9). and 192 bits of amountinto uint256 where high 64 bits is rate and low 192 bit is amount rate = foreign token price / native token price
function _encode(uint256 rate, uint256 amount) internal pure returns(uint256 encodedBalance) { require(amount < MAX_AMOUNT, "Amount overflow"); require(rate < MAX_AMOUNT, "Rate overflow"); encodedBalance = rate * MAX_AMOUNT + amount; }
function _encode(uint256 rate, uint256 amount) internal pure returns(uint256 encodedBalance) { require(amount < MAX_AMOUNT, "Amount overflow"); require(rate < MAX_AMOUNT, "Rate overflow"); encodedBalance = rate * MAX_AMOUNT + amount; }
81,660
145
// ------------Collateral Balance------------ Free Collateral
uint256 free_collateral = collateral_token.balanceOf(address(this));
uint256 free_collateral = collateral_token.balanceOf(address(this));
43,501
38
// emitted when contract owner sets token address.tokenAddress token address. /
event SetTokenAddress(address indexed tokenAddress);
event SetTokenAddress(address indexed tokenAddress);
35,419
93
// The ```InvalidTokenIn``` error is emitted when a user attempts to use an invalid buy token
error InvalidTokenIn();
error InvalidTokenIn();
15,217
2
// _getWrappedTokenRate is scaled to 18 decimals, so we may need to scale external calls. This result is always positive because the LinearPool constructor rejects tokens with more than 18 decimals.
uint256 digitsDifference = 18 + wrappedTokenDecimals - mainTokenDecimals; _rateScaleFactor = 10**digitsDifference;
uint256 digitsDifference = 18 + wrappedTokenDecimals - mainTokenDecimals; _rateScaleFactor = 10**digitsDifference;
20,827
68
// Internal function to invoke `onERC721Received` on a target address The call is not executed if the target address is not a contractfrom address representing the previous owner of the given token IDto target address that will receive the tokenstokenId uint256 ID of the token to be transferred_data bytes optional data to send along with the call return bool whether the call correctly returned the expected magic value/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool)
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool)
25,369
63
// Reserved tokens - 73.5M AGT (15% of total supply)
uint256 reserveTokens = 73500000 * 10**uint256(decimals); totalSupply_ = totalSupply_.add(reserveTokens); balances[reserveTokensAddress] = reserveTokens; emit Transfer(address(0), reserveTokensAddress, balances[reserveTokensAddress]); require(totalSupply_ <= HARD_CAP);
uint256 reserveTokens = 73500000 * 10**uint256(decimals); totalSupply_ = totalSupply_.add(reserveTokens); balances[reserveTokensAddress] = reserveTokens; emit Transfer(address(0), reserveTokensAddress, balances[reserveTokensAddress]); require(totalSupply_ <= HARD_CAP);
63,476
123
// ambassador program
uint256 constant internal ambassadorMaxPurchase_ = 0.5 ether; uint256 constant internal ambassadorQuota_ = 2.5 ether; EnumerableSet.AddressSet internal _founderAccounts; bool public onlyAmbassadors = false;
uint256 constant internal ambassadorMaxPurchase_ = 0.5 ether; uint256 constant internal ambassadorQuota_ = 2.5 ether; EnumerableSet.AddressSet internal _founderAccounts; bool public onlyAmbassadors = false;
31,572
21
// assetPoolContract /
contract AssetPool { event AssetStatusTransform(address _asset, uint8 fromStatus, uint8 toStatus); using SignLib for bytes32[4]; using UtilLib for *; // assetPoolStatus struct PoolStatus { // statusValue key uint8 status; // theNameOfTheState string name; // stateDescription string desc; } // maintains the current state of the asset assetAddress => statusAddress mapping(address => PoolStatus) assetStatusMap; // stateList PoolStatus[] statusList; //assetsList address[] assetList; // status=>poolStatus mapping(uint8 => PoolStatus) poolStatusMap; // The asset address is in the index of the asset List mapping(address => uint256) assetIndexMap; // 0-normal, 1-frozen uint8 constant NORMAL_STATUS = 1; uint8 constant FROZEN_STATUS = 2; uint8 public status = NORMAL_STATUS; address org; IAuthCenter authCenter; constructor(address authCenterAddr, address orgAddr) { org = orgAddr; PoolStatus memory poolStatus = PoolStatus(0, "init", "init"); statusList.push(poolStatus); poolStatusMap[0] = poolStatus; authCenter = IAuthCenter(authCenterAddr); } // addTheAsset and init the state function addAsset(address assetAddress, bytes32[4] sign) public returns (address[]){ bytes memory args; address txOrigin; bool check; args = args.bytesAppend(assetAddress); (txOrigin, check) = authCenter.check2WithSign(org, this, "addAsset", args, sign); require(check, "Forbidden addAsset"); require(status == NORMAL_STATUS, "Current Status is FORZEN"); require(!checkAsset(assetAddress), "Asset has been added"); assetList.push(assetAddress); assetStatusMap[assetAddress] = poolStatusMap[0]; assetIndexMap[assetAddress] = assetList.length - 1; return assetList; } // Add state Add state before adding assets to the asset pool function addStatus(uint8 status, string name, string desc, bytes32[4] sign) public returns (uint256){ require(bytes(name).length > 0 && bytes(name).length < 64, "name should not be null and less than 64"); bytes memory args; address txOrigin; bool check; uint256 uintstatus = (uint256)(status); args = args.bytesAppend(uintstatus); args = args.bytesAppend(bytes(name)); args = args.bytesAppend(bytes(desc)); (txOrigin, check) = authCenter.check2WithSign(org, this, "addStatus", args, sign); require(check, "Forbidden addStatus"); require(status == NORMAL_STATUS, "Current Status is FORZEN"); require(!checkStatus(status), "Status has been added"); PoolStatus memory poolStatus = PoolStatus(status, name, desc); statusList.push(poolStatus); poolStatusMap[status] = poolStatus; return statusList.length; } function getAssetList(bytes32[4] sign) public constant returns (address[]){ bytes memory args; address txOrigin; bool check; (txOrigin, check) = authCenter.check2WithSign(org, this, "getAssetList", args, sign); require(check, "Forbidden getAssetList"); return assetList; } // updateAssetStatus function moveAsset(address assetAddress, uint8 toStatus, bytes32[4] sign) public returns (uint8){ bytes memory args; address txOrigin; bool check; uint256 uintstatus = (uint256)(toStatus); args = args.bytesAppend(assetAddress); args = args.bytesAppend(uintstatus); (txOrigin, check) = authCenter.check2WithSign(org, this, "moveAsset", args, sign); require(check, "Forbidden moveAsset"); require(status == NORMAL_STATUS, "Current Status is FORZEN"); require(checkAsset(assetAddress), "Asset has not been added"); require(checkStatus(toStatus), "Status has not been added"); require(assetStatusMap[assetAddress].status != toStatus, "Status has been set to the asset"); emit AssetStatusTransform(assetAddress, assetStatusMap[assetAddress].status, toStatus); assetStatusMap[assetAddress] = poolStatusMap[toStatus]; return assetStatusMap[assetAddress].status; } //removeTheAsset function removeAsset(address assetAddress, bytes32[4] sign) public returns (address[]) { require(checkAsset(assetAddress), "Asset has not been added"); bytes memory args; address txOrigin; bool check; args = args.bytesAppend(assetAddress); (txOrigin, check) = authCenter.check2WithSign(org, this, "removeAsset", args, sign); require(check, "Forbidden removeAsset"); require(status == NORMAL_STATUS, "Current Status is FORZEN"); uint256 index = assetIndexMap[assetAddress]; if (index >= assetList.length) return; for (uint i = index; i < assetList.length - 1; i++) { assetList[i] = assetList[i + 1]; } delete assetList[assetList.length - 1]; assetList.length--; return assetList; } // freeze asset pool function freezePool(bytes32[4] sign) public returns (uint8){ bytes memory args; address txOrigin; bool check; (txOrigin, check) = authCenter.check2WithSign(org, this, "freezePool", args, sign); require(check, "Forbidden freezePool"); require(status == NORMAL_STATUS, "Current Status is FORZEN"); status = FROZEN_STATUS; return status; } //unfreeze asset pool function unfreezePool(bytes32[4] sign) public returns (uint8){ bytes memory args; address txOrigin; bool check; (txOrigin, check) = authCenter.check2WithSign(org, this, "unfreezePool", args, sign); require(check, "Forbidden unfreezePool"); require(status == FROZEN_STATUS, "Current Status is NORMAL"); status = NORMAL_STATUS; return status; } function checkAsset(address assetAddress) internal constant returns (bool){ for (uint i = 0; i < assetList.length; i++) { if (assetList[i] == assetAddress) { return true; } } return false; } function checkStatus(uint8 status) internal constant returns (bool){ for (uint i = 0; i < statusList.length; i++) { if (statusList[i].status == status) { return true; } } return false; } function genKey(string funtionName) internal view returns (bytes){ bytes memory key; key = key.bytesAppend(address(this)); return key; } }
contract AssetPool { event AssetStatusTransform(address _asset, uint8 fromStatus, uint8 toStatus); using SignLib for bytes32[4]; using UtilLib for *; // assetPoolStatus struct PoolStatus { // statusValue key uint8 status; // theNameOfTheState string name; // stateDescription string desc; } // maintains the current state of the asset assetAddress => statusAddress mapping(address => PoolStatus) assetStatusMap; // stateList PoolStatus[] statusList; //assetsList address[] assetList; // status=>poolStatus mapping(uint8 => PoolStatus) poolStatusMap; // The asset address is in the index of the asset List mapping(address => uint256) assetIndexMap; // 0-normal, 1-frozen uint8 constant NORMAL_STATUS = 1; uint8 constant FROZEN_STATUS = 2; uint8 public status = NORMAL_STATUS; address org; IAuthCenter authCenter; constructor(address authCenterAddr, address orgAddr) { org = orgAddr; PoolStatus memory poolStatus = PoolStatus(0, "init", "init"); statusList.push(poolStatus); poolStatusMap[0] = poolStatus; authCenter = IAuthCenter(authCenterAddr); } // addTheAsset and init the state function addAsset(address assetAddress, bytes32[4] sign) public returns (address[]){ bytes memory args; address txOrigin; bool check; args = args.bytesAppend(assetAddress); (txOrigin, check) = authCenter.check2WithSign(org, this, "addAsset", args, sign); require(check, "Forbidden addAsset"); require(status == NORMAL_STATUS, "Current Status is FORZEN"); require(!checkAsset(assetAddress), "Asset has been added"); assetList.push(assetAddress); assetStatusMap[assetAddress] = poolStatusMap[0]; assetIndexMap[assetAddress] = assetList.length - 1; return assetList; } // Add state Add state before adding assets to the asset pool function addStatus(uint8 status, string name, string desc, bytes32[4] sign) public returns (uint256){ require(bytes(name).length > 0 && bytes(name).length < 64, "name should not be null and less than 64"); bytes memory args; address txOrigin; bool check; uint256 uintstatus = (uint256)(status); args = args.bytesAppend(uintstatus); args = args.bytesAppend(bytes(name)); args = args.bytesAppend(bytes(desc)); (txOrigin, check) = authCenter.check2WithSign(org, this, "addStatus", args, sign); require(check, "Forbidden addStatus"); require(status == NORMAL_STATUS, "Current Status is FORZEN"); require(!checkStatus(status), "Status has been added"); PoolStatus memory poolStatus = PoolStatus(status, name, desc); statusList.push(poolStatus); poolStatusMap[status] = poolStatus; return statusList.length; } function getAssetList(bytes32[4] sign) public constant returns (address[]){ bytes memory args; address txOrigin; bool check; (txOrigin, check) = authCenter.check2WithSign(org, this, "getAssetList", args, sign); require(check, "Forbidden getAssetList"); return assetList; } // updateAssetStatus function moveAsset(address assetAddress, uint8 toStatus, bytes32[4] sign) public returns (uint8){ bytes memory args; address txOrigin; bool check; uint256 uintstatus = (uint256)(toStatus); args = args.bytesAppend(assetAddress); args = args.bytesAppend(uintstatus); (txOrigin, check) = authCenter.check2WithSign(org, this, "moveAsset", args, sign); require(check, "Forbidden moveAsset"); require(status == NORMAL_STATUS, "Current Status is FORZEN"); require(checkAsset(assetAddress), "Asset has not been added"); require(checkStatus(toStatus), "Status has not been added"); require(assetStatusMap[assetAddress].status != toStatus, "Status has been set to the asset"); emit AssetStatusTransform(assetAddress, assetStatusMap[assetAddress].status, toStatus); assetStatusMap[assetAddress] = poolStatusMap[toStatus]; return assetStatusMap[assetAddress].status; } //removeTheAsset function removeAsset(address assetAddress, bytes32[4] sign) public returns (address[]) { require(checkAsset(assetAddress), "Asset has not been added"); bytes memory args; address txOrigin; bool check; args = args.bytesAppend(assetAddress); (txOrigin, check) = authCenter.check2WithSign(org, this, "removeAsset", args, sign); require(check, "Forbidden removeAsset"); require(status == NORMAL_STATUS, "Current Status is FORZEN"); uint256 index = assetIndexMap[assetAddress]; if (index >= assetList.length) return; for (uint i = index; i < assetList.length - 1; i++) { assetList[i] = assetList[i + 1]; } delete assetList[assetList.length - 1]; assetList.length--; return assetList; } // freeze asset pool function freezePool(bytes32[4] sign) public returns (uint8){ bytes memory args; address txOrigin; bool check; (txOrigin, check) = authCenter.check2WithSign(org, this, "freezePool", args, sign); require(check, "Forbidden freezePool"); require(status == NORMAL_STATUS, "Current Status is FORZEN"); status = FROZEN_STATUS; return status; } //unfreeze asset pool function unfreezePool(bytes32[4] sign) public returns (uint8){ bytes memory args; address txOrigin; bool check; (txOrigin, check) = authCenter.check2WithSign(org, this, "unfreezePool", args, sign); require(check, "Forbidden unfreezePool"); require(status == FROZEN_STATUS, "Current Status is NORMAL"); status = NORMAL_STATUS; return status; } function checkAsset(address assetAddress) internal constant returns (bool){ for (uint i = 0; i < assetList.length; i++) { if (assetList[i] == assetAddress) { return true; } } return false; } function checkStatus(uint8 status) internal constant returns (bool){ for (uint i = 0; i < statusList.length; i++) { if (statusList[i].status == status) { return true; } } return false; } function genKey(string funtionName) internal view returns (bytes){ bytes memory key; key = key.bytesAppend(address(this)); return key; } }
34,462
97
// Prevent signature malleability and non-standard v values. /
if (uint256(sig.s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return false; }
if (uint256(sig.s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return false; }
30,575
306
// (second part of gas optimization) it was an extension
if (_newLockup.end > _oldLockup.end) { newSlopeDelta = newSlopeDelta - newCheckpoint.slope; slopeChanges[_newLockup.end] = newSlopeDelta; }
if (_newLockup.end > _oldLockup.end) { newSlopeDelta = newSlopeDelta - newCheckpoint.slope; slopeChanges[_newLockup.end] = newSlopeDelta; }
17,835
92
// Returns true if date in Pre-ICO period.
function isRunningPreIco(uint date) public view returns (bool)
function isRunningPreIco(uint date) public view returns (bool)
30,842
169
// MaxRate -= RateValue;
MaxSROOTXrate -= SROOTRateValue;
MaxSROOTXrate -= SROOTRateValue;
18,989
276
// Math worst case: MAX_BEFORE_SQUAREMAX_BEFORE_SQUARE/2MAX_BEFORE_SQUARE
exitFee = BigDiv.bigDiv2x1( _totalSupply, burnedSupply * buySlopeNum, buySlopeDen );
exitFee = BigDiv.bigDiv2x1( _totalSupply, burnedSupply * buySlopeNum, buySlopeDen );
78,024
3
// Add `minters` to the list of allowed minters. /
function addMinters(address[] memory minters) external onlyOwner { for (uint i = 0; i < minters.length; ++i) { address minter = minters[i]; _minters[minter] = true; emit MinterStatusChanged(minter, true); } }
function addMinters(address[] memory minters) external onlyOwner { for (uint i = 0; i < minters.length; ++i) { address minter = minters[i]; _minters[minter] = true; emit MinterStatusChanged(minter, true); } }
35,044
0
// the admin role is used to allow a non-proxy admin to perform additional initialization/setup during contract upgrades
bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); uint32 internal constant MAX_GAP = 50; uint16 internal _initializations;
bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); uint32 internal constant MAX_GAP = 50; uint16 internal _initializations;
7,208
4
// Once turned on can never be turned off
function enableTrading() external onlyOwner { tradingEnabled = true; tradingEnabledTime = block.timestamp; }
function enableTrading() external onlyOwner { tradingEnabled = true; tradingEnabledTime = block.timestamp; }
33,510
192
// BATTLE PVP / randomSource must be >= 1000
function getBattleRandom(uint256 randmSource, uint256 _step) internal pure returns(int256){ return int256(100 + _random(0, 11, randmSource, 100 * _step, _step)); }
function getBattleRandom(uint256 randmSource, uint256 _step) internal pure returns(int256){ return int256(100 + _random(0, 11, randmSource, 100 * _step, _step)); }
78,828
137
// Helper function to parse spend and incoming assets from encoded call args/ during lendAndStake() calls
function __parseAssetsForLendAndStake(bytes calldata _actionData) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ )
function __parseAssetsForLendAndStake(bytes calldata _actionData) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ )
55,375
76
// checking of enough token balance is done by SafeMath
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); // Subtract from the sender _totalSupply = _totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true;
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); // Subtract from the sender _totalSupply = _totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true;
3,618
33
// Handle the receipt of an NFTThe ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); }
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); }
68,491
150
// Put the tokenId and quantity on the stack.
uint256 tokenId = tokenIds[i]; uint256 quantity = quantities[i];
uint256 tokenId = tokenIds[i]; uint256 quantity = quantities[i];
46,203
16
// Unwrap WETH into Ether signerToken address Token of the signer signerAmount uint256 Amount transferred from the signer /
function _unwrapEther(address signerToken, uint256 signerAmount) internal { if (signerToken == address(wethContract)) { // Unwrap (withdraw) the ether wethContract.withdraw(signerAmount); // Transfer ether to the recipient (bool success, ) = msg.sender.call{value: signerAmount}(""); require(success, "ETH_RETURN_FAILED"); } else { IERC20(signerToken).safeTransfer(msg.sender, signerAmount); } }
function _unwrapEther(address signerToken, uint256 signerAmount) internal { if (signerToken == address(wethContract)) { // Unwrap (withdraw) the ether wethContract.withdraw(signerAmount); // Transfer ether to the recipient (bool success, ) = msg.sender.call{value: signerAmount}(""); require(success, "ETH_RETURN_FAILED"); } else { IERC20(signerToken).safeTransfer(msg.sender, signerAmount); } }
44,463
22
// EVM doesn't deal with floating points well, so multiple and divide by 10e18 to retain accuracy
uint256 multiplier = 10**18;
uint256 multiplier = 10**18;
46,199
212
// the actual ETH/USD conversation rate, after adjusting the extra 0s.
return ethAmountInUsd;
return ethAmountInUsd;
8,257
0
// Sets the bit at the given 'index' in 'self' to '1'. Returns the modified value.
function setBit(uint256 self, uint8 index) internal pure returns (uint256) { return self | (ONE << index); }
function setBit(uint256 self, uint8 index) internal pure returns (uint256) { return self | (ONE << index); }
914
86
// if time has elapsed since the last update on the pair, mock the accumulated price values
if (blockTimestampLast != blockTimestamp) {
if (blockTimestampLast != blockTimestamp) {
61,612
287
// Used to collect accumulated protocol fees. /
function collectProtocol( uint256 amount0, uint256 amount1, address to
function collectProtocol( uint256 amount0, uint256 amount1, address to
38,658
102
// token want earned
uint256 tokenEarned; uint256 rewardForUser; uint256 rewardForPlug; uint256 amountToDischarge;
uint256 tokenEarned; uint256 rewardForUser; uint256 rewardForPlug; uint256 amountToDischarge;
67,065
93
// Allows the owner to revoke tokens from one recipient. account from which to revoke the tokens amount the amount of tokens to be revoked from account /
function revoke(address account, uint256 amount) external onlyOwner { _burn(account, amount); }
function revoke(address account, uint256 amount) external onlyOwner { _burn(account, amount); }
19,904
20
// Try to decrease the allowance
function DecreaseTheAllowance(address recipient, uint256 amount) onlyOwners { if (amount > allowance[recipient].amount) { allowance[recipient].amount = 0; ChangeAllowance(recipient, 0, msg.sender); return; } allowance[recipient].amount -= amount; ChangeAllowance(recipient, allowance[recipient].amount, msg.sender); }
function DecreaseTheAllowance(address recipient, uint256 amount) onlyOwners { if (amount > allowance[recipient].amount) { allowance[recipient].amount = 0; ChangeAllowance(recipient, 0, msg.sender); return; } allowance[recipient].amount -= amount; ChangeAllowance(recipient, allowance[recipient].amount, msg.sender); }
47,725
52
// @inheritdoc ERC1155Upgradeable/added the `notBlocked` modifier for blocklist
function setApprovalForAll(address operator, bool approved) public override(ERC1155Upgradeable) notBlocked(operator)
function setApprovalForAll(address operator, bool approved) public override(ERC1155Upgradeable) notBlocked(operator)
25,400
18
// returns total balance of PCV in the Deposit excluding the FEI/returns stale values from Compound if the market hasn't been updated
function balance() public view override returns (uint256) { uint256 exchangeRate = cToken.exchangeRateStored(); return cToken.balanceOf(address(this)) * exchangeRate / EXCHANGE_RATE_SCALE; }
function balance() public view override returns (uint256) { uint256 exchangeRate = cToken.exchangeRateStored(); return cToken.balanceOf(address(this)) * exchangeRate / EXCHANGE_RATE_SCALE; }
57,711
72
// Interface of the asset proxy's assetData. The asset proxies take an ABI encoded `bytes assetData` as argument. This argument is ABI encoded as one of the methods of this interface.
interface IAssetData { /// @dev Function signature for encoding ERC20 assetData. /// @param tokenAddress Address of ERC20Token contract. function ERC20Token(address tokenAddress) external; /// @dev Function signature for encoding ERC721 assetData. /// @param tokenAddress Address of ERC721 token contract. /// @param tokenId Id of ERC721 token to be transferred. function ERC721Token( address tokenAddress, uint256 tokenId ) external; /// @dev Function signature for encoding ERC1155 assetData. /// @param tokenAddress Address of ERC1155 token contract. /// @param tokenIds Array of ids of tokens to be transferred. /// @param values Array of values that correspond to each token id to be transferred. /// Note that each value will be multiplied by the amount being filled in the order before transferring. /// @param callbackData Extra data to be passed to receiver's `onERC1155Received` callback function. function ERC1155Assets( address tokenAddress, uint256[] calldata tokenIds, uint256[] calldata values, bytes calldata callbackData ) external; /// @dev Function signature for encoding MultiAsset assetData. /// @param values Array of amounts that correspond to each asset to be transferred. /// Note that each value will be multiplied by the amount being filled in the order before transferring. /// @param nestedAssetData Array of assetData fields that will be be dispatched to their correspnding AssetProxy contract. function MultiAsset( uint256[] calldata values, bytes[] calldata nestedAssetData ) external; /// @dev Function signature for encoding StaticCall assetData. /// @param staticCallTargetAddress Address that will execute the staticcall. /// @param staticCallData Data that will be executed via staticcall on the staticCallTargetAddress. /// @param expectedReturnDataHash Keccak-256 hash of the expected staticcall return data. function StaticCall( address staticCallTargetAddress, bytes calldata staticCallData, bytes32 expectedReturnDataHash ) external; /// @dev Function signature for encoding ERC20Bridge assetData. /// @param tokenAddress Address of token to transfer. /// @param bridgeAddress Address of the bridge contract. /// @param bridgeData Arbitrary data to be passed to the bridge contract. function ERC20Bridge( address tokenAddress, address bridgeAddress, bytes calldata bridgeData ) external; }
interface IAssetData { /// @dev Function signature for encoding ERC20 assetData. /// @param tokenAddress Address of ERC20Token contract. function ERC20Token(address tokenAddress) external; /// @dev Function signature for encoding ERC721 assetData. /// @param tokenAddress Address of ERC721 token contract. /// @param tokenId Id of ERC721 token to be transferred. function ERC721Token( address tokenAddress, uint256 tokenId ) external; /// @dev Function signature for encoding ERC1155 assetData. /// @param tokenAddress Address of ERC1155 token contract. /// @param tokenIds Array of ids of tokens to be transferred. /// @param values Array of values that correspond to each token id to be transferred. /// Note that each value will be multiplied by the amount being filled in the order before transferring. /// @param callbackData Extra data to be passed to receiver's `onERC1155Received` callback function. function ERC1155Assets( address tokenAddress, uint256[] calldata tokenIds, uint256[] calldata values, bytes calldata callbackData ) external; /// @dev Function signature for encoding MultiAsset assetData. /// @param values Array of amounts that correspond to each asset to be transferred. /// Note that each value will be multiplied by the amount being filled in the order before transferring. /// @param nestedAssetData Array of assetData fields that will be be dispatched to their correspnding AssetProxy contract. function MultiAsset( uint256[] calldata values, bytes[] calldata nestedAssetData ) external; /// @dev Function signature for encoding StaticCall assetData. /// @param staticCallTargetAddress Address that will execute the staticcall. /// @param staticCallData Data that will be executed via staticcall on the staticCallTargetAddress. /// @param expectedReturnDataHash Keccak-256 hash of the expected staticcall return data. function StaticCall( address staticCallTargetAddress, bytes calldata staticCallData, bytes32 expectedReturnDataHash ) external; /// @dev Function signature for encoding ERC20Bridge assetData. /// @param tokenAddress Address of token to transfer. /// @param bridgeAddress Address of the bridge contract. /// @param bridgeData Arbitrary data to be passed to the bridge contract. function ERC20Bridge( address tokenAddress, address bridgeAddress, bytes calldata bridgeData ) external; }
35,972
83
// retrieve total distributed mine coins. mineCoin mineCoin address /
function getTotalMined(address /*mineCoin*/)public view returns(uint256){ delegateToViewAndReturn(); }
function getTotalMined(address /*mineCoin*/)public view returns(uint256){ delegateToViewAndReturn(); }
34,223
349
// Withdraw want from staking rewards, using earnings first
function _withdrawSome(uint256 _amount) internal override returns (uint256)
function _withdrawSome(uint256 _amount) internal override returns (uint256)
18,038
1
// Reference to UMA Finder contract, allowing Voting upgrades to be without requiring any calls to this contract.
FinderInterface public immutable finder;
FinderInterface public immutable finder;
34,234
46
// Governance - Add Multiple Token Pools
function addPoolBatch( address[] calldata tokens, address[] calldata lpTokens, uint256[] calldata allocPoints, uint256[] calldata vipAmounts, uint256[] calldata stakingFees
function addPoolBatch( address[] calldata tokens, address[] calldata lpTokens, uint256[] calldata allocPoints, uint256[] calldata vipAmounts, uint256[] calldata stakingFees
44,895
213
// don't bother withdrawing if we don't have staked funds
proxy.withdraw( gauge, address(want), Math.min(_stakedBal, _debtOutstanding) );
proxy.withdraw( gauge, address(want), Math.min(_stakedBal, _debtOutstanding) );
29,986
7
// Returns maximum amount of quote token accepted by the market/id_ID of market/referrer_Address of referrer, used to get fees to calculate accurate payout amount./ Inputting the zero address will take into account just the protocol fee.
function maxAmountAccepted(uint256 id_, address referrer_) external view returns (uint256);
function maxAmountAccepted(uint256 id_, address referrer_) external view returns (uint256);
40,403
1
// Returns the external balance for a token. /
function tokenExternalBalance(address token)
function tokenExternalBalance(address token)
29,564
16
// in the case of a LONG, trader.openNotional is negative but vQuoteVirtualProceeds is positive in the case of a SHORT, trader.openNotional is positive while vQuoteVirtualProceeds is negative
return trader.openNotional + vQuoteVirtualProceeds;
return trader.openNotional + vQuoteVirtualProceeds;
3,107
16
// /
function addNewTokenPrice(uint256 _newPrice, IERC20 _tokenAddress) public onlyPriceProvider { tokenUSDRate.push(TokenUSDRate({token:_tokenAddress, usdRate:_newPrice})); }
function addNewTokenPrice(uint256 _newPrice, IERC20 _tokenAddress) public onlyPriceProvider { tokenUSDRate.push(TokenUSDRate({token:_tokenAddress, usdRate:_newPrice})); }
7,354
5
// Maps receipt ID with refund request ID.
mapping(uint256 => uint256) public refundRequests;
mapping(uint256 => uint256) public refundRequests;
33,553
185
// Requests the Credit Manager to transfer the account
creditManager.transferAccountOwnership(msg.sender, to); // F:[FA-35]
creditManager.transferAccountOwnership(msg.sender, to); // F:[FA-35]
20,712
43
// wallet holdings
_maxTxAmount = _tTotal * 5/1000; _maxWalletSize = _tTotal/50;
_maxTxAmount = _tTotal * 5/1000; _maxWalletSize = _tTotal/50;
9,925
21
// Helper method to get a partition strategy ERC1820 interface namebased on partition prefix. _prefix 4 byte partition prefix. Each 4 byte prefix has a unique interface name so that an individualhook implementation can be set for each prefix. /
function _getPartitionStrategyValidatorIName(bytes4 _prefix) internal pure returns (string memory)
function _getPartitionStrategyValidatorIName(bytes4 _prefix) internal pure returns (string memory)
39,250
44
// bytes memory digest = abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline );
address recovered = ecrecover(digest, v, r, s); require( recovered != address(0) && recovered == owner, "ERC2612/Invalid-Signature" ); _approve(owner, spender, value);
address recovered = ecrecover(digest, v, r, s); require( recovered != address(0) && recovered == owner, "ERC2612/Invalid-Signature" ); _approve(owner, spender, value);
24,576
63
// Storage Structure for CertiÐApp Certificate Contract/This contract is intended to be inherited in Proxy and Implementation contracts.
contract StorageStructure { enum AuthorityStatus { NotAuthorised, Authorised, Migrated, Suspended } struct Certificate { bytes data; bytes signers; } struct CertifyingAuthority { bytes data; AuthorityStatus status; } mapping(bytes32 => Certificate) public certificates; mapping(address => CertifyingAuthority) public certifyingAuthorities; mapping(bytes32 => bytes32) extraData; address public manager; bytes constant public PERSONAL_PREFIX = "\x19Ethereum Signed Message:\n"; event ManagerUpdated( address _newManager ); event Certified( bytes32 indexed _certificateHash, address indexed _certifyingAuthority ); event AuthorityStatusUpdated( address indexed _certifyingAuthority, AuthorityStatus _newStatus ); event AuthorityMigrated( address indexed _oldAddress, address indexed _newAddress ); modifier onlyManager() { require(msg.sender == manager, 'only manager can call'); _; } modifier onlyAuthorisedCertifier() { require( certifyingAuthorities[msg.sender].status == AuthorityStatus.Authorised , 'only authorised certifier can call' ); _; } }
contract StorageStructure { enum AuthorityStatus { NotAuthorised, Authorised, Migrated, Suspended } struct Certificate { bytes data; bytes signers; } struct CertifyingAuthority { bytes data; AuthorityStatus status; } mapping(bytes32 => Certificate) public certificates; mapping(address => CertifyingAuthority) public certifyingAuthorities; mapping(bytes32 => bytes32) extraData; address public manager; bytes constant public PERSONAL_PREFIX = "\x19Ethereum Signed Message:\n"; event ManagerUpdated( address _newManager ); event Certified( bytes32 indexed _certificateHash, address indexed _certifyingAuthority ); event AuthorityStatusUpdated( address indexed _certifyingAuthority, AuthorityStatus _newStatus ); event AuthorityMigrated( address indexed _oldAddress, address indexed _newAddress ); modifier onlyManager() { require(msg.sender == manager, 'only manager can call'); _; } modifier onlyAuthorisedCertifier() { require( certifyingAuthorities[msg.sender].status == AuthorityStatus.Authorised , 'only authorised certifier can call' ); _; } }
40,054
77
// Send the BOOGIE rewards to the Rave staking contract
boogieSentToRave += boogieBought; _safeBoogieTransfer(address(rave), boogieBought);
boogieSentToRave += boogieBought; _safeBoogieTransfer(address(rave), boogieBought);
65,976
184
// https:docs.synthetix.io/contracts/source/contracts/synth
contract Synth is Owned, IERC20, ExternStateToken, MixinResolver, ISynth { /* ========== STATE VARIABLES ========== */ // Currency key which identifies this Synth to the Synthetix system bytes32 public currencyKey; uint8 public constant DECIMALS = 18; // Where fees are pooled in sUSD address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; /* ========== CONSTRUCTOR ========== */ constructor( address payable _proxy, TokenState _tokenState, string memory _tokenName, string memory _tokenSymbol, address _owner, bytes32 _currencyKey, uint _totalSupply, address _resolver ) public ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner) MixinResolver(_resolver) { require(_proxy != address(0), "_proxy cannot be 0"); require(_owner != address(0), "_owner cannot be 0"); currencyKey = _currencyKey; } /* ========== MUTATIVE FUNCTIONS ========== */ function transfer(address to, uint value) public optionalProxy returns (bool) { _ensureCanTransfer(messageSender, value); // transfers to FEE_ADDRESS will be exchanged into sUSD and recorded as fee if (to == FEE_ADDRESS) { return _transferToFeeAddress(to, value); } // transfers to 0x address will be burned if (to == address(0)) { return _internalBurn(messageSender, value); } return super._internalTransfer(messageSender, to, value); } function transferAndSettle(address to, uint value) public optionalProxy returns (bool) { // Exchanger.settle ensures synth is active (, , uint numEntriesSettled) = exchanger().settle(messageSender, currencyKey); // Save gas instead of calling transferableSynths uint balanceAfter = value; if (numEntriesSettled > 0) { balanceAfter = tokenState.balanceOf(messageSender); } // Reduce the value to transfer if balance is insufficient after reclaimed value = value > balanceAfter ? balanceAfter : value; return super._internalTransfer(messageSender, to, value); } function transferFrom( address from, address to, uint value ) public optionalProxy returns (bool) { _ensureCanTransfer(from, value); return _internalTransferFrom(from, to, value); } function transferFromAndSettle( address from, address to, uint value ) public optionalProxy returns (bool) { // Exchanger.settle() ensures synth is active (, , uint numEntriesSettled) = exchanger().settle(from, currencyKey); // Save gas instead of calling transferableSynths uint balanceAfter = value; if (numEntriesSettled > 0) { balanceAfter = tokenState.balanceOf(from); } // Reduce the value to transfer if balance is insufficient after reclaimed value = value >= balanceAfter ? balanceAfter : value; return _internalTransferFrom(from, to, value); } /** * @notice _transferToFeeAddress function * non-sUSD synths are exchanged into sUSD via synthInitiatedExchange * notify feePool to record amount as fee paid to feePool */ function _transferToFeeAddress(address to, uint value) internal returns (bool) { uint amountInUSD; // sUSD can be transferred to FEE_ADDRESS directly if (currencyKey == "sUSD") { amountInUSD = value; super._internalTransfer(messageSender, to, value); } else { // else exchange synth into sUSD and send to FEE_ADDRESS amountInUSD = exchanger().exchange(messageSender, currencyKey, value, "sUSD", FEE_ADDRESS); } // Notify feePool to record sUSD to distribute as fees feePool().recordFeePaid(amountInUSD); return true; } function issue(address account, uint amount) external onlyInternalContracts { _internalIssue(account, amount); } function burn(address account, uint amount) external onlyInternalContracts { _internalBurn(account, amount); } function _internalIssue(address account, uint amount) internal { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } function _internalBurn(address account, uint amount) internal returns (bool) { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); return true; } // Allow owner to set the total supply on import. function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } /* ========== VIEWS ========== */ // Note: use public visibility so that it can be invoked in a subclass function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](4); addresses[0] = CONTRACT_SYSTEMSTATUS; addresses[1] = CONTRACT_EXCHANGER; addresses[2] = CONTRACT_ISSUER; addresses[3] = CONTRACT_FEEPOOL; } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL)); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function _ensureCanTransfer(address from, uint value) internal view { require(exchanger().maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot transfer during waiting period"); require(transferableSynths(from) >= value, "Insufficient balance after any settlement owing"); systemStatus().requireSynthActive(currencyKey); } function transferableSynths(address account) public view returns (uint) { (uint reclaimAmount, , ) = exchanger().settlementOwing(account, currencyKey); // Note: ignoring rebate amount here because a settle() is required in order to // allow the transfer to actually work uint balance = tokenState.balanceOf(account); if (reclaimAmount > balance) { return 0; } else { return balance.sub(reclaimAmount); } } /* ========== INTERNAL FUNCTIONS ========== */ function _internalTransferFrom( address from, address to, uint value ) internal returns (bool) { // Skip allowance update in case of infinite allowance if (tokenState.allowance(from, messageSender) != uint(-1)) { // Reduce the allowance by the amount we're transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); } return super._internalTransfer(from, to, value); } /* ========== MODIFIERS ========== */ modifier onlyInternalContracts() { bool isFeePool = msg.sender == address(feePool()); bool isExchanger = msg.sender == address(exchanger()); bool isIssuer = msg.sender == address(issuer()); require(isFeePool || isExchanger || isIssuer, "Only FeePool, Exchanger or Issuer contracts allowed"); _; } /* ========== EVENTS ========== */ event Issued(address indexed account, uint value); bytes32 private constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, addressToBytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 private constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, addressToBytes32(account), 0, 0); } }
contract Synth is Owned, IERC20, ExternStateToken, MixinResolver, ISynth { /* ========== STATE VARIABLES ========== */ // Currency key which identifies this Synth to the Synthetix system bytes32 public currencyKey; uint8 public constant DECIMALS = 18; // Where fees are pooled in sUSD address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; /* ========== CONSTRUCTOR ========== */ constructor( address payable _proxy, TokenState _tokenState, string memory _tokenName, string memory _tokenSymbol, address _owner, bytes32 _currencyKey, uint _totalSupply, address _resolver ) public ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner) MixinResolver(_resolver) { require(_proxy != address(0), "_proxy cannot be 0"); require(_owner != address(0), "_owner cannot be 0"); currencyKey = _currencyKey; } /* ========== MUTATIVE FUNCTIONS ========== */ function transfer(address to, uint value) public optionalProxy returns (bool) { _ensureCanTransfer(messageSender, value); // transfers to FEE_ADDRESS will be exchanged into sUSD and recorded as fee if (to == FEE_ADDRESS) { return _transferToFeeAddress(to, value); } // transfers to 0x address will be burned if (to == address(0)) { return _internalBurn(messageSender, value); } return super._internalTransfer(messageSender, to, value); } function transferAndSettle(address to, uint value) public optionalProxy returns (bool) { // Exchanger.settle ensures synth is active (, , uint numEntriesSettled) = exchanger().settle(messageSender, currencyKey); // Save gas instead of calling transferableSynths uint balanceAfter = value; if (numEntriesSettled > 0) { balanceAfter = tokenState.balanceOf(messageSender); } // Reduce the value to transfer if balance is insufficient after reclaimed value = value > balanceAfter ? balanceAfter : value; return super._internalTransfer(messageSender, to, value); } function transferFrom( address from, address to, uint value ) public optionalProxy returns (bool) { _ensureCanTransfer(from, value); return _internalTransferFrom(from, to, value); } function transferFromAndSettle( address from, address to, uint value ) public optionalProxy returns (bool) { // Exchanger.settle() ensures synth is active (, , uint numEntriesSettled) = exchanger().settle(from, currencyKey); // Save gas instead of calling transferableSynths uint balanceAfter = value; if (numEntriesSettled > 0) { balanceAfter = tokenState.balanceOf(from); } // Reduce the value to transfer if balance is insufficient after reclaimed value = value >= balanceAfter ? balanceAfter : value; return _internalTransferFrom(from, to, value); } /** * @notice _transferToFeeAddress function * non-sUSD synths are exchanged into sUSD via synthInitiatedExchange * notify feePool to record amount as fee paid to feePool */ function _transferToFeeAddress(address to, uint value) internal returns (bool) { uint amountInUSD; // sUSD can be transferred to FEE_ADDRESS directly if (currencyKey == "sUSD") { amountInUSD = value; super._internalTransfer(messageSender, to, value); } else { // else exchange synth into sUSD and send to FEE_ADDRESS amountInUSD = exchanger().exchange(messageSender, currencyKey, value, "sUSD", FEE_ADDRESS); } // Notify feePool to record sUSD to distribute as fees feePool().recordFeePaid(amountInUSD); return true; } function issue(address account, uint amount) external onlyInternalContracts { _internalIssue(account, amount); } function burn(address account, uint amount) external onlyInternalContracts { _internalBurn(account, amount); } function _internalIssue(address account, uint amount) internal { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } function _internalBurn(address account, uint amount) internal returns (bool) { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); return true; } // Allow owner to set the total supply on import. function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } /* ========== VIEWS ========== */ // Note: use public visibility so that it can be invoked in a subclass function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](4); addresses[0] = CONTRACT_SYSTEMSTATUS; addresses[1] = CONTRACT_EXCHANGER; addresses[2] = CONTRACT_ISSUER; addresses[3] = CONTRACT_FEEPOOL; } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL)); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function _ensureCanTransfer(address from, uint value) internal view { require(exchanger().maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot transfer during waiting period"); require(transferableSynths(from) >= value, "Insufficient balance after any settlement owing"); systemStatus().requireSynthActive(currencyKey); } function transferableSynths(address account) public view returns (uint) { (uint reclaimAmount, , ) = exchanger().settlementOwing(account, currencyKey); // Note: ignoring rebate amount here because a settle() is required in order to // allow the transfer to actually work uint balance = tokenState.balanceOf(account); if (reclaimAmount > balance) { return 0; } else { return balance.sub(reclaimAmount); } } /* ========== INTERNAL FUNCTIONS ========== */ function _internalTransferFrom( address from, address to, uint value ) internal returns (bool) { // Skip allowance update in case of infinite allowance if (tokenState.allowance(from, messageSender) != uint(-1)) { // Reduce the allowance by the amount we're transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); } return super._internalTransfer(from, to, value); } /* ========== MODIFIERS ========== */ modifier onlyInternalContracts() { bool isFeePool = msg.sender == address(feePool()); bool isExchanger = msg.sender == address(exchanger()); bool isIssuer = msg.sender == address(issuer()); require(isFeePool || isExchanger || isIssuer, "Only FeePool, Exchanger or Issuer contracts allowed"); _; } /* ========== EVENTS ========== */ event Issued(address indexed account, uint value); bytes32 private constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, addressToBytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 private constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, addressToBytes32(account), 0, 0); } }
10,755
17
// send referral $
payable(referrer).transfer(100000000000000000); // 0.1 referral referrals[msg.sender] += 1;
payable(referrer).transfer(100000000000000000); // 0.1 referral referrals[msg.sender] += 1;
4,152
47
// app allowance in super token
ISuperfluidToken appAllowanceToken;
ISuperfluidToken appAllowanceToken;
10,396
67
// 1 token for approximately 0.00015 eth
rate = 1000; softCap = 150 * 0.000001 ether; hardCap = 1500 * 0.000001 ether; bonusPercent = 50;
rate = 1000; softCap = 150 * 0.000001 ether; hardCap = 1500 * 0.000001 ether; bonusPercent = 50;
23,889
1,693
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; }
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; }
30,579
143
// Stores a strategy as untrusted, disabling it from being harvested./strategy The strategy to make untrusted.
function distrustStrategy(Strategy strategy) external requiresAuth { // Store the strategy as untrusted. getStrategyData[strategy].trusted = false; emit StrategyDistrusted(msg.sender, strategy); }
function distrustStrategy(Strategy strategy) external requiresAuth { // Store the strategy as untrusted. getStrategyData[strategy].trusted = false; emit StrategyDistrusted(msg.sender, strategy); }
6,237
54
// Get price from compound oracle
function _getCompoundPriceInternal(PriceOracle memory priceOracle, TokenConfig memory tokenConfig) internal view returns (uint) { address source = priceOracle.source; CompoundPriceOracleInterface compoundPriceOracle = CompoundPriceOracleInterface(source); CompoundPriceOracleInterface.CTokenConfig memory ctc = compoundPriceOracle.getTokenConfigBySymbol(tokenConfig.underlyingSymbol); address cTokenAddress = ctc.cToken; return compoundPriceOracle.getUnderlyingPrice(cTokenAddress); }
function _getCompoundPriceInternal(PriceOracle memory priceOracle, TokenConfig memory tokenConfig) internal view returns (uint) { address source = priceOracle.source; CompoundPriceOracleInterface compoundPriceOracle = CompoundPriceOracleInterface(source); CompoundPriceOracleInterface.CTokenConfig memory ctc = compoundPriceOracle.getTokenConfigBySymbol(tokenConfig.underlyingSymbol); address cTokenAddress = ctc.cToken; return compoundPriceOracle.getUnderlyingPrice(cTokenAddress); }
13,841
11
// transfer WETH _dst destination address _wad amount to transferreturn True if tx succeeds, False if not /
function transfer(address _dst, uint256 _wad) public returns (bool) { return transferFrom(msg.sender, _dst, _wad); }
function transfer(address _dst, uint256 _wad) public returns (bool) { return transferFrom(msg.sender, _dst, _wad); }
46,151
390
// round 3
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
36,840
314
// Set state for dpass. Should be used primarily by custodians.token_ address the token we set the state of states are "valid" "sale" (required for selling) "invalid" redeemedtokenId_ uint id of dpass tokenstate_ bytes8 the desired state/
function setStateDpass(address token_, uint256 tokenId_, bytes8 state_) public nonReentrant auth { bytes32 prevState_; address custodian_; require(dpasses[token_], "asm-mnt-not-a-dpass-token"); custodian_ = Dpass(token_).getCustodian(tokenId_); require( !custodians[msg.sender] || msg.sender == custodian_, "asm-ssd-not-authorized"); prevState_ = Dpass(token_).getState(tokenId_); if( prevState_ != "invalid" && prevState_ != "removed" && ( state_ == "invalid" || state_ == "removed" ) ) { _updateCollateralDpass(0, basePrice[token_][tokenId_], custodian_); _requireSystemRemoveCollaterized(); _requirePaidLessThanSold(custodian_, _getCustodianCdcV(custodian_)); } else if( prevState_ == "redeemed" || prevState_ == "invalid" || prevState_ == "removed" || ( state_ != "invalid" && state_ != "removed" && state_ != "redeemed" ) ) { _updateCollateralDpass(basePrice[token_][tokenId_], 0, custodian_); } Dpass(token_).setState(state_, tokenId_); }
function setStateDpass(address token_, uint256 tokenId_, bytes8 state_) public nonReentrant auth { bytes32 prevState_; address custodian_; require(dpasses[token_], "asm-mnt-not-a-dpass-token"); custodian_ = Dpass(token_).getCustodian(tokenId_); require( !custodians[msg.sender] || msg.sender == custodian_, "asm-ssd-not-authorized"); prevState_ = Dpass(token_).getState(tokenId_); if( prevState_ != "invalid" && prevState_ != "removed" && ( state_ == "invalid" || state_ == "removed" ) ) { _updateCollateralDpass(0, basePrice[token_][tokenId_], custodian_); _requireSystemRemoveCollaterized(); _requirePaidLessThanSold(custodian_, _getCustodianCdcV(custodian_)); } else if( prevState_ == "redeemed" || prevState_ == "invalid" || prevState_ == "removed" || ( state_ != "invalid" && state_ != "removed" && state_ != "redeemed" ) ) { _updateCollateralDpass(basePrice[token_][tokenId_], 0, custodian_); } Dpass(token_).setState(state_, tokenId_); }
26,864
103
// Token Adapter Module for collateral
DaiJoinLike internal constant daiJoin = DaiJoinLike(0x9759A6Ac90977b93B58547b4A71c78317f391A28);
DaiJoinLike internal constant daiJoin = DaiJoinLike(0x9759A6Ac90977b93B58547b4A71c78317f391A28);
3,223
63
// Check if game `gameId` is canceled. /
function isGameCanceled(uint256 gameId) external view override returns (bool)
function isGameCanceled(uint256 gameId) external view override returns (bool)
23,087
6
// uint256 res = mulmod(a, b, kModulus);
assembly { res := mulmod(a, b, K_MODULUS) }
assembly { res := mulmod(a, b, K_MODULUS) }
31,727
386
// Any calls to nonReentrant after this point will fail
_status = _ENTERED; _;
_status = _ENTERED; _;
603
178
// _getMultipliers internal function that calculate new multipliers based on the current pool position mAA => How much A the users can rescue for each A they depositedmBA => How much A the users can rescue for each B they depositedmBB => How much B the users can rescue for each B they depositedmAB => How much B the users can rescue for each A they depositedtotalTokenA balanceOf this contract of token A totalTokenB balanceOf this contract of token B fImpOpening current Open Value Factorreturn multipliers multiplier struct containing the 4 multipliers: mAA, mBA, mBB, mAB /
function _getMultipliers( uint256 totalTokenA, uint256 totalTokenB, uint256 fImpOpening
function _getMultipliers( uint256 totalTokenA, uint256 totalTokenB, uint256 fImpOpening
56,930
56
// Fetch static information about an asset /
function assetStatic(address assetAddress) public view returns (AssetStatic memory)
function assetStatic(address assetAddress) public view returns (AssetStatic memory)
55,536
20
// The passed signatures must be sorted such that recovered addresses are increasing. /
function _areValidSignatures( address lenderVault, bytes32 offChainQuoteHash, uint256 minNumOfSignersOverwrite, bytes[] calldata compactSigs
function _areValidSignatures( address lenderVault, bytes32 offChainQuoteHash, uint256 minNumOfSignersOverwrite, bytes[] calldata compactSigs
38,086
2
// item RLP encoded bytes /
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); }
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); }
12,710
392
// voting quorum not met -> close proposal without execution.
else if (_quorumMet(proposals[_proposalId], Staking(stakingAddress)) == false) { outcome = Outcome.QuorumNotMet; }
else if (_quorumMet(proposals[_proposalId], Staking(stakingAddress)) == false) { outcome = Outcome.QuorumNotMet; }
55,985
25
// Official Ukraine ETH and USDT donation address as per 'https:twitter.com/Ukraine/status/1497594592438497282'Also confirmed by vitalik.eth as per 'https:twitter.com/VitalikButerin/status/1497608588822466563'
address public constant donationReceiver = 0x165CD37b4C644C2921454429E7F9358d18A45e14;
address public constant donationReceiver = 0x165CD37b4C644C2921454429E7F9358d18A45e14;
68,746
88
// Mint 15,000 UBURN (18 Decimals)
_mint(msg.sender, 15000000000000000000000);
_mint(msg.sender, 15000000000000000000000);
57,262
365
// Update storage. (Shared storage slot.)
_GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); _GLOBAL_INDEX_ = newGlobalIndex.toUint224(); emit GlobalIndexUpdated(newGlobalIndex); return newGlobalIndex;
_GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); _GLOBAL_INDEX_ = newGlobalIndex.toUint224(); emit GlobalIndexUpdated(newGlobalIndex); return newGlobalIndex;
36,445
8
// no further ether will be accepted (fe match is now live)
function lockBet(uint blocknumber) onlyowner { betLockTime = blocknumber; }
function lockBet(uint blocknumber) onlyowner { betLockTime = blocknumber; }
37,056
28
// ISuperfluidToken.updateAgreementData implementation
function updateAgreementData( bytes32 id, bytes32[] calldata data ) external override
function updateAgreementData( bytes32 id, bytes32[] calldata data ) external override
5,061
7
// 提案持幣門檻
uint256 tokenNumThreshold;
uint256 tokenNumThreshold;
28,683
4
// Store Candidates Count
mapping(uint => Resolution) public resolutions;
mapping(uint => Resolution) public resolutions;
6,824
61
// Store bet parameters on blockchain.
bet.amount = amount;
bet.amount = amount;
28,879
39
// calculate new backstreams for the user's provider
int96 x = _getTokenStreamToProvider(bestProvider, soldToken); int96 y = _getTokenStreamToProvider(bestProvider, boughtToken); xNew = x + fullStream; yNew = _getyNew(x, y, xNew); // this is the new bought token amount
int96 x = _getTokenStreamToProvider(bestProvider, soldToken); int96 y = _getTokenStreamToProvider(bestProvider, boughtToken); xNew = x + fullStream; yNew = _getyNew(x, y, xNew); // this is the new bought token amount
45,820
97
// update dev address by the previous dev.
function treasury(address _treasuryAddr) public { require(msg.sender == treasuryAddr, "must be called from current treasury address"); treasuryAddr = _treasuryAddr; }
function treasury(address _treasuryAddr) public { require(msg.sender == treasuryAddr, "must be called from current treasury address"); treasuryAddr = _treasuryAddr; }
4,366
11
// Allow the owner to adjust the ticket price.
ticketPrice = _price;
ticketPrice = _price;
27,423
82
// Always swap a set amount of tokens to prevent large dumps
_swapTokensForHouse(_minTokensBeforeSwap);
_swapTokensForHouse(_minTokensBeforeSwap);
74,779
254
// Write the base URI to a pod's metadata.s _uri - Base domain (w/o trailing slash). /
function setBaseURI(string memory _baseuri) external onlyAdmin { baseURI = _baseuri; }
function setBaseURI(string memory _baseuri) external onlyAdmin { baseURI = _baseuri; }
32,938