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
153
// Bond a validator _valAddr the address of the validator /
function _bondValidator(address _valAddr) private { bondedValAddrs.push(_valAddr); _setBondedValidator(_valAddr); }
function _bondValidator(address _valAddr) private { bondedValAddrs.push(_valAddr); _setBondedValidator(_valAddr); }
83,032
5
// Bump version TODO
CHANGELOG.setVersion("X.X.X");
CHANGELOG.setVersion("X.X.X");
23,220
85
// Set UNIV2DAIETH Osm in the OsmMom for new ilk !!!!!!!! Only if PIP_UNIV2DAIETH = Osm
OsmMomAbstract(OSM_MOM).setOsm(ILK_UNIV2DAIETH_A, PIP_UNIV2DAIETH);
OsmMomAbstract(OSM_MOM).setOsm(ILK_UNIV2DAIETH_A, PIP_UNIV2DAIETH);
36,234
8
// ,d8888bP88.88P 8P 88P'88P 88. 8P 88d888888P’88?8b88888888?88'd88’d8888b d8888b ’88b8 d8888b. 8P88P88Pd8P' ?88 88P'88 ?8pd8b_,dP,8b d8888P 88bd88 d88 88.88b88b,8b ,8b’d88' 88P`?8888P’. b’?888P'’8888p.`?888P' ,8P’SmartWay Rocket (only for rocket members) /
library SafeMath { function mul(uint a, uint b) internal pure returns(uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns(uint) { require(b > 0); uint c = a / b; require(a == b * c + a % b); return c; } function sub(uint a, uint b) internal pure returns(uint) { require(b <= a); return a - b; } function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns(uint64) { return a >= b ? a: b; } function min64(uint64 a, uint64 b) internal pure returns(uint64) { return a < b ? a: b; } function max256(uint256 a, uint256 b) internal pure returns(uint256) { return a >= b ? a: b; } function min256(uint256 a, uint256 b) internal pure returns(uint256) { return a < b ? a: b; } }
library SafeMath { function mul(uint a, uint b) internal pure returns(uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns(uint) { require(b > 0); uint c = a / b; require(a == b * c + a % b); return c; } function sub(uint a, uint b) internal pure returns(uint) { require(b <= a); return a - b; } function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns(uint64) { return a >= b ? a: b; } function min64(uint64 a, uint64 b) internal pure returns(uint64) { return a < b ? a: b; } function max256(uint256 a, uint256 b) internal pure returns(uint256) { return a >= b ? a: b; } function min256(uint256 a, uint256 b) internal pure returns(uint256) { return a < b ? a: b; } }
85,808
47
// Contract address of the associated ERC20 token
address token;
address token;
6,342
38
// send `value` token to `to` from `msg.sender`to The address of the recipientvalue The amount of token to be transferred return the transaction address and send the event as Transfer
function transfer(address to, uint256 value) public canTradable returns (bool success) { require ( balances[msg.sender] >= value && value > 0 ); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); Transfer(msg.sender, to, value); return true; }
function transfer(address to, uint256 value) public canTradable returns (bool success) { require ( balances[msg.sender] >= value && value > 0 ); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); Transfer(msg.sender, to, value); return true; }
11,593
19
// Request for randomness. /
function getRandomNumber(uint256 userProvidedSeed) internal returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) > fee, "Error, not enough LINK - fill contract with faucet"); return requestRandomness(keyHash, fee, userProvidedSeed); }
function getRandomNumber(uint256 userProvidedSeed) internal returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) > fee, "Error, not enough LINK - fill contract with faucet"); return requestRandomness(keyHash, fee, userProvidedSeed); }
13,704
1
// function interface to process exits. exitId unique id for exit per tx type. vaultId id of the vault that funds the exit. token address of the token contract. /
function processExit(uint160 exitId, uint256 vaultId, address token) external;
function processExit(uint160 exitId, uint256 vaultId, address token) external;
31,978
202
// ======== Royalties =========
address public royaltyAddress; uint256 public royaltyPercent; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri, address _proxyRegistryAddress
address public royaltyAddress; uint256 public royaltyPercent; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri, address _proxyRegistryAddress
40,368
36
// You can't change crowdsale contract when migration is in progress.
if(currentPhase == Phase.Migrating) revert(); crowdsaleManager = _mgr;
if(currentPhase == Phase.Migrating) revert(); crowdsaleManager = _mgr;
54,197
129
// Approve the spending of all assets by their corresponding cToken, if for some reason is it necessary. /
function safeApproveAllTokens() external { uint256 assetCount = assetsMapped.length; for (uint256 i = 0; i < assetCount; i++) { address asset = assetsMapped[i]; address cToken = assetToPToken[asset]; // Safe approval IERC20(asset).safeApprove(cToken, 0); IERC20(asset).safeApprove(cToken, uint256(-1)); } }
function safeApproveAllTokens() external { uint256 assetCount = assetsMapped.length; for (uint256 i = 0; i < assetCount; i++) { address asset = assetsMapped[i]; address cToken = assetToPToken[asset]; // Safe approval IERC20(asset).safeApprove(cToken, 0); IERC20(asset).safeApprove(cToken, uint256(-1)); } }
39,586
160
// Raise given number x into power specified as a simple fraction y/z and thenmultiply the result by the normalization factor 2^(128(1 - y/z)).Revert if z is zero, or if both x and y are zeros.x number to raise into given power y/z y numerator of the power to raise x into z denominator of the power to raise x intoreturn x raised into power y/z and then multiplied by 2^(128(1 - y/z)) /
function pow(uint128 x, uint128 y, uint128 z)
function pow(uint128 x, uint128 y, uint128 z)
38,751
59
// Block specific data that is only used to help process the block on-chain. It is not used as input for the circuits and it is not necessary for data-availability. This bytes array contains the abi encoded AuxiliaryData[] data.
bytes auxiliaryData;
bytes auxiliaryData;
3,467
10
// Is NFT's `contractAddress` Whitelisted For Mint/ contractAddress to check/return True if contract whitelisted
function isContractWhitelisted(address contractAddress) external view returns (bool)
function isContractWhitelisted(address contractAddress) external view returns (bool)
17,833
122
// Bootstrap is a stash of coins to provide initial liquidity to the uniswap pool and launch campiagn
percentBootstrap = _percentBootstrap;
percentBootstrap = _percentBootstrap;
54,056
203
// 13hs EST 28/10/2021
uint256 public EARLY_BIRD_START = 1635388609; // 1635440400;
uint256 public EARLY_BIRD_START = 1635388609; // 1635440400;
38,286
160
// Function to transfer tokens. to The address that will receive the tokens. value The amount of tokens to transfer. /
function transfer(address to, uint256 value) external override returns (bool)
function transfer(address to, uint256 value) external override returns (bool)
64,550
43
// Used by the issuer to set the controller addresses _controller address of the controller /
function setController(address _controller) external;
function setController(address _controller) external;
9,541
13
// ERC20 interface /
contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); }/**
contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); }/**
39,110
24
// Withdraw the whole balance of the contract according to the pre-defined basis points./In case someone (either service, or client, or referrer) fails to accept ether,/ the owner will be able to recover some of their share./ This scenario is very unlikely. It can only happen if that someone is a contract/ whose receive function changed its behavior since FeeDistributor's initialization./ It can never happen unless the receiving party themselves wants it to happen./ We strongly recommend against intentional reverts in the receive function/ because the remaining parties might call `withdraw` again multiple times without waiting/ for the owner to recover
function withdraw() external nonReentrant { if (s_clientConfig.recipient == address(0)) { revert FeeDistributor__ClientNotSet(); } // get the contract's balance uint256 balance = address(this).balance; if (balance == 0) { // revert if there is no ether to withdraw revert FeeDistributor__NothingToWithdraw(); } if (s_validatorData.collateralReturnedValue / COLLATERAL < s_validatorData.exitedCount) { // If exited some of the validators voluntarily. // In case of slashing, the client can still call the voluntaryExit function to claim // non-splittable balance up to 32 ETH per validator, // thus getting some slashing protection covered from EL rewards. uint112 collateralValueToReturn = uint112( s_validatorData.exitedCount * COLLATERAL - s_validatorData.collateralReturnedValue ); if (collateralValueToReturn > balance) { collateralValueToReturn = uint112(balance); } // Send collaterals to client bool success = P2pAddressLib._sendValue( s_clientConfig.recipient, collateralValueToReturn ); if (success) { // It's OK to violate the checks-effects-interactions pattern here thanks to nonReentrant s_validatorData.collateralReturnedValue += collateralValueToReturn; emit ContractWcFeeDistributor__CollateralReturnedValueIncreased( collateralValueToReturn, s_validatorData.collateralReturnedValue ); if (s_validatorData.cooldownUntil != 0) { // reset cooldownUntil if the client received their collaterals s_validatorData.cooldownUntil = 0; } } else { if (s_validatorData.cooldownUntil == 0) { // set cooldownUntil if it has not been set before s_validatorData.cooldownUntil = uint80(block.timestamp + COOLDOWN); } emit ContractWcFeeDistributor__ClientRevertOnCollateralReceive(s_validatorData.cooldownUntil); if (block.timestamp < s_validatorData.cooldownUntil) { return; // prevent further ETH sending } } // Balance remainder to split balance = address(this).balance; } // how much should client get uint256 clientAmount = (balance * s_clientConfig.basisPoints) / 10000; // how much should service get uint256 serviceAmount = balance - clientAmount; // how much should referrer get uint256 referrerAmount; if (s_referrerConfig.recipient != address(0)) { // if there is a referrer referrerAmount = (balance * s_referrerConfig.basisPoints) / 10000; serviceAmount -= referrerAmount; // Send ETH to referrer. Ignore the possible yet unlikely revert in the receive function. P2pAddressLib._sendValue( s_referrerConfig.recipient, referrerAmount ); } // Send ETH to service. Ignore the possible yet unlikely revert in the receive function. P2pAddressLib._sendValue( i_service, serviceAmount ); // Send ETH to client. Ignore the possible yet unlikely revert in the receive function. P2pAddressLib._sendValue( s_clientConfig.recipient, clientAmount ); emit FeeDistributor__Withdrawn( serviceAmount, clientAmount, referrerAmount ); }
function withdraw() external nonReentrant { if (s_clientConfig.recipient == address(0)) { revert FeeDistributor__ClientNotSet(); } // get the contract's balance uint256 balance = address(this).balance; if (balance == 0) { // revert if there is no ether to withdraw revert FeeDistributor__NothingToWithdraw(); } if (s_validatorData.collateralReturnedValue / COLLATERAL < s_validatorData.exitedCount) { // If exited some of the validators voluntarily. // In case of slashing, the client can still call the voluntaryExit function to claim // non-splittable balance up to 32 ETH per validator, // thus getting some slashing protection covered from EL rewards. uint112 collateralValueToReturn = uint112( s_validatorData.exitedCount * COLLATERAL - s_validatorData.collateralReturnedValue ); if (collateralValueToReturn > balance) { collateralValueToReturn = uint112(balance); } // Send collaterals to client bool success = P2pAddressLib._sendValue( s_clientConfig.recipient, collateralValueToReturn ); if (success) { // It's OK to violate the checks-effects-interactions pattern here thanks to nonReentrant s_validatorData.collateralReturnedValue += collateralValueToReturn; emit ContractWcFeeDistributor__CollateralReturnedValueIncreased( collateralValueToReturn, s_validatorData.collateralReturnedValue ); if (s_validatorData.cooldownUntil != 0) { // reset cooldownUntil if the client received their collaterals s_validatorData.cooldownUntil = 0; } } else { if (s_validatorData.cooldownUntil == 0) { // set cooldownUntil if it has not been set before s_validatorData.cooldownUntil = uint80(block.timestamp + COOLDOWN); } emit ContractWcFeeDistributor__ClientRevertOnCollateralReceive(s_validatorData.cooldownUntil); if (block.timestamp < s_validatorData.cooldownUntil) { return; // prevent further ETH sending } } // Balance remainder to split balance = address(this).balance; } // how much should client get uint256 clientAmount = (balance * s_clientConfig.basisPoints) / 10000; // how much should service get uint256 serviceAmount = balance - clientAmount; // how much should referrer get uint256 referrerAmount; if (s_referrerConfig.recipient != address(0)) { // if there is a referrer referrerAmount = (balance * s_referrerConfig.basisPoints) / 10000; serviceAmount -= referrerAmount; // Send ETH to referrer. Ignore the possible yet unlikely revert in the receive function. P2pAddressLib._sendValue( s_referrerConfig.recipient, referrerAmount ); } // Send ETH to service. Ignore the possible yet unlikely revert in the receive function. P2pAddressLib._sendValue( i_service, serviceAmount ); // Send ETH to client. Ignore the possible yet unlikely revert in the receive function. P2pAddressLib._sendValue( s_clientConfig.recipient, clientAmount ); emit FeeDistributor__Withdrawn( serviceAmount, clientAmount, referrerAmount ); }
27,983
161
// Clears the token filtering for a specific contract. /
function clearTokenFilters(address contractAddress) external { uint256 contractIndex = _coreAddressIndices[contractAddress]; require( // Reentrancy guard. We require the contract to be frozen for extra security. _status == S_FROZEN // Caller must be an admin. && (_addressRoles[msg.sender] & R_IS_ADMIN) == R_IS_ADMIN // Make sure the contract is tracked. && contractIndex > 0 , "Not authorized"); // Clear the filters. delete _filteringDataStart[contractAddress]; delete _filteringDataEnd[contractAddress]; // Hello world! emit FilteringCleared(contractAddress); }
function clearTokenFilters(address contractAddress) external { uint256 contractIndex = _coreAddressIndices[contractAddress]; require( // Reentrancy guard. We require the contract to be frozen for extra security. _status == S_FROZEN // Caller must be an admin. && (_addressRoles[msg.sender] & R_IS_ADMIN) == R_IS_ADMIN // Make sure the contract is tracked. && contractIndex > 0 , "Not authorized"); // Clear the filters. delete _filteringDataStart[contractAddress]; delete _filteringDataEnd[contractAddress]; // Hello world! emit FilteringCleared(contractAddress); }
30,490
70
// measure the carbon intensity of a tracker NFT.This is a recursive function that cycle through all previous trackerIds trackerId to measure tokenTypeId measure total carbonIntensity of tracker token for tokenTypeId outputs (2. offset credits, audited emission certificates, carbon tracker tokens)/
function _carbonIntensity(uint trackerId, uint8 tokenTypeId, uint[MAX_NESTED_TRACKERS] memory usedTrackerIds)
function _carbonIntensity(uint trackerId, uint8 tokenTypeId, uint[MAX_NESTED_TRACKERS] memory usedTrackerIds)
1,254
7
// Returns the current global Fees and Bootstrap rewards state /calculated to the latest block, may differ from the state read/ return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive/ return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive/ return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive/ return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive/ return lastAssigned is the time the calculation was done to (typically the latest block time)
function getFeesAndBootstrapState() external view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned );
function getFeesAndBootstrapState() external view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned );
18,004
35
// Check if contract exists at that address
uint32 codeSize; assembly { codeSize := extcodesize(contractAddress) }
uint32 codeSize; assembly { codeSize := extcodesize(contractAddress) }
21,667
101
// on sell
if (isLiquidityPool(to_) && _totalSellTaxBasisPoints() > 0) { if (projectSellTaxBasisPoints > 0) { uint256 projectTax = ((sentAmount_ * projectSellTaxBasisPoints) / BP_DENOM); projectTaxPendingSwap += uint128(projectTax); tax += projectTax; }
if (isLiquidityPool(to_) && _totalSellTaxBasisPoints() > 0) { if (projectSellTaxBasisPoints > 0) { uint256 projectTax = ((sentAmount_ * projectSellTaxBasisPoints) / BP_DENOM); projectTaxPendingSwap += uint128(projectTax); tax += projectTax; }
31,407
9
// Returns the message with id `_id` received from chain `_chainName`. /
function getReceivedMessage(string calldata _chainName, uint256 _id) view external returns (ReceivedMessage memory);
function getReceivedMessage(string calldata _chainName, uint256 _id) view external returns (ReceivedMessage memory);
9,854
49
// See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is notrequired by the EIP. See the note at the beginning of {ERC20}. Requirements: - `sender` and `recipient` cannot be the zero address.- `sender` must have a balance of at least `amount`.- the caller must have allowance for ``sender``'s tokens of at least`amount`. /
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; }
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; }
120
474
// ========== VIEWS ========== / Needed as a FRAX AMO
function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { // Dummy values here. FPI is not FRAX and should not be treated as FRAX collateral frax_val_e18 = 1e18; collat_val_e18 = 1e18; }
function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { // Dummy values here. FPI is not FRAX and should not be treated as FRAX collateral frax_val_e18 = 1e18; collat_val_e18 = 1e18; }
12,235
97
// sets the maximum percentage that an individual token holder can hold_maxHolderCount is the new maximum amount a holder can hold/
function changeHolderCount(uint256 _maxHolderCount) public withPerm(ADMIN) { emit LogModifyHolderCount(maxHolderCount, _maxHolderCount); maxHolderCount = _maxHolderCount; }
function changeHolderCount(uint256 _maxHolderCount) public withPerm(ADMIN) { emit LogModifyHolderCount(maxHolderCount, _maxHolderCount); maxHolderCount = _maxHolderCount; }
73,248
20
// Deploy a new contract with the initialization code stored in theruntime code at the specified initialization runtime storage contract tothe home address corresponding to a given key. Two conditions must be met:the submitter must be designated as the controller of the home address(with the initial controller set to the address corresponding to the first20 bytes of the key), and there must not be a contract currently deployedat the home address. These conditions can be checked by calling`getHomeAddressInformation` and `isDeployable` with the same key. key bytes32 The unique value used to derive the home address. initializationRuntimeStorageContract address The storage contractwith runtime
function deployViaExistingRuntimeStorageContract(
function deployViaExistingRuntimeStorageContract(
44,057
46
// fallback for when a transfer happens with payouts remaining
mapping(address => uint256) public unclaimedPayoutTotals;
mapping(address => uint256) public unclaimedPayoutTotals;
8,786
87
// ERC20Decimals interfaceId: bytes4(keccak256("decimals()"))
_registerInterface(0x313ce567);
_registerInterface(0x313ce567);
7,295
4
// init/
constructor() public { owner = msg.sender; }
constructor() public { owner = msg.sender; }
1,432
34
// Internal: Set the period in epochs that need to pass before fees in rebate pool can be claimed. _channelDisputeEpochs Period in epochs /
function _setChannelDisputeEpochs(uint32 _channelDisputeEpochs) private { require(_channelDisputeEpochs > 0, "!channelDisputeEpochs"); channelDisputeEpochs = _channelDisputeEpochs; emit ParameterUpdated("channelDisputeEpochs"); }
function _setChannelDisputeEpochs(uint32 _channelDisputeEpochs) private { require(_channelDisputeEpochs > 0, "!channelDisputeEpochs"); channelDisputeEpochs = _channelDisputeEpochs; emit ParameterUpdated("channelDisputeEpochs"); }
9,313
21
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
uint public creationBlock;
19,977
30
// Initialize is separate from constructor to allow timer to be started at a later date (after tokens are loaded)
require(msg.sender == deployer, "Can only be initialized by deployer"); require(initialized == false, "Already initialized"); initialized = true; lastUnlock = block.timestamp; nextUnlock = lastUnlock.add(interval); uint256 balance = token.balanceOf(address(this)); require(balance > 0, "Tokens are not loaded yet"); // Check to ensure tokens are loaded into contract distributionAmount = balance.div(totalCycles);
require(msg.sender == deployer, "Can only be initialized by deployer"); require(initialized == false, "Already initialized"); initialized = true; lastUnlock = block.timestamp; nextUnlock = lastUnlock.add(interval); uint256 balance = token.balanceOf(address(this)); require(balance > 0, "Tokens are not loaded yet"); // Check to ensure tokens are loaded into contract distributionAmount = balance.div(totalCycles);
28,752
13
// results in test.x becoming == 1 and test.y becoming 0.
(success,) = address(test).call{value: 1}(abi.encodeWithSignature("nonExistingFunction()"));
(success,) = address(test).call{value: 1}(abi.encodeWithSignature("nonExistingFunction()"));
16,285
115
// preparing vesting schedules
for (uint256 i = 0; i < numberOfPayouts; i++) { vestingInfo.vestingSchedules.push(VestingSchedule({ unlockPercentage: (i + 1) * _payOutPercentage, unlockTime: st + (i * _payOutInterval) }));
for (uint256 i = 0; i < numberOfPayouts; i++) { vestingInfo.vestingSchedules.push(VestingSchedule({ unlockPercentage: (i + 1) * _payOutPercentage, unlockTime: st + (i * _payOutInterval) }));
44,442
18
// Mint tokens, after accumulating rewards for an user and update the rewards per token accumulator.
function _mint(address dst, uint256 wad) internal virtual override returns (bool)
function _mint(address dst, uint256 wad) internal virtual override returns (bool)
35,121
175
// load cached from memory
exchange = uniswapExchanges[token];
exchange = uniswapExchanges[token];
1,585
696
// ERC20 decimals function. Returns the same number of decimals as the position's owedToken returnThe number of decimal places, or revert if the baseToken has no such function. /
function decimals() external view returns (uint8);
function decimals() external view returns (uint8);
46,151
32
// _totalSupply = addSafe(_totalSupply, tokens);
Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value);
Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value);
84,942
16
// will trigger a transaction
test.t(1);
test.t(1);
28,185
36
// RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1))); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _;
require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1))); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _;
24,048
47
// Set the contract that can call release and make the token transferable. Design choice. Allow reset the release agent to fix fat finger mistakes. /
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { require(addr != 0x0); // We don't do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; }
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { require(addr != 0x0); // We don't do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; }
35,073
48
// Verify whether a given team occupies a given spot.
function verifyPosition( uint8 spot, uint64 angelId, uint64 petId, uint64 accessoryId
function verifyPosition( uint8 spot, uint64 angelId, uint64 petId, uint64 accessoryId
9,727
7
// Revert with an ABI encoded Solidity error with a message/ that fits into 32-bytes.// An ABI encoded Solidity error has the following memory layout:// ------------+----------------------------------/byte range | value/ ------------+----------------------------------/0x00..0x04 |selector("Error(string)")/0x04..0x24 |string offset (always 0x20)/0x24..0x44 |string length/0x44..0x64 | string value, padded to 32-bytes
function revertWithMessage(length, message) { mstore(0x00, "\x08\xc3\x79\xa0") mstore(0x04, 0x20) mstore(0x24, length) mstore(0x44, message) revert(0x00, 0x64) }
function revertWithMessage(length, message) { mstore(0x00, "\x08\xc3\x79\xa0") mstore(0x04, 0x20) mstore(0x24, length) mstore(0x44, message) revert(0x00, 0x64) }
1,261
59
// Called when new token are issued
event Issue(uint amount);
event Issue(uint amount);
2,605
6
// GoldMiner earn 10000 $SILVER per day
uint public constant DAILY_SILVER_RATE = 10000 ether; uint public constant MINIMUM_TIME_TO_EXIT = 2 days; uint public constant TAX_PERCENTAGE = 20; uint public constant MAXIMUM_GLOBAL_SILVER = 2400000000 ether; uint public totalSilverEarned; uint public lastClaimTimestamp;
uint public constant DAILY_SILVER_RATE = 10000 ether; uint public constant MINIMUM_TIME_TO_EXIT = 2 days; uint public constant TAX_PERCENTAGE = 20; uint public constant MAXIMUM_GLOBAL_SILVER = 2400000000 ether; uint public totalSilverEarned; uint public lastClaimTimestamp;
39,223
2
// Example: Only allow the "admin" role to call this function/
function helloWorld(address account) external view onlyRole(DEFAULT_ADMIN_ROLE) returns (uint) { return balanceOf(account); }
function helloWorld(address account) external view onlyRole(DEFAULT_ADMIN_ROLE) returns (uint) { return balanceOf(account); }
27,505
230
// Level 3 costs steel
KingOfEthResource(contractFor(ResourceType.STEEL)).interfaceBurnTokens( _player , 1 );
KingOfEthResource(contractFor(ResourceType.STEEL)).interfaceBurnTokens( _player , 1 );
26,261
209
// Library used to query support of an interface declared via {IERC165}. As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
11,705
181
// Set generation to be the lower of the two parents
uint256 gen = mon1.gen.add(1); if (mon2.gen < mon1.gen) { gen = mon2.gen.add(1); }
uint256 gen = mon1.gen.add(1); if (mon2.gen < mon1.gen) { gen = mon2.gen.add(1); }
5,245
37
// todo: 计算正确的值
return (0, 0);
return (0, 0);
3,752
83
// add to assignmentIndex and assign that as assignmentID
stud.assignmentIndex = stud.assignmentIndex.add(1); assignmentID = stud.assignmentIndex;
stud.assignmentIndex = stud.assignmentIndex.add(1); assignmentID = stud.assignmentIndex;
16,763
85
// 当天是否已经领取过
mapping(uint256=>mapping(address=>bool)) obtainRecord; uint256 tokenTotal = 1000; uint256[] ids; uint256[10] rankingAward = [10,5,3,1,1,1,1,1,1,1]; uint256 lastStrawAward = 5;
mapping(uint256=>mapping(address=>bool)) obtainRecord; uint256 tokenTotal = 1000; uint256[] ids; uint256[10] rankingAward = [10,5,3,1,1,1,1,1,1,1]; uint256 lastStrawAward = 5;
14,572
49
// Sells the remaining collateral tokens for weth, withdraws that and returns native eth to the user_collateralTokenAddress of the collateral token _collateralRemainingAmount of the collateral token remaining after buying required debt tokens _originalSender Address of the original sender to return the eth to _minAmountOutputToken Minimum amount of output token to return to user _swapData Data (token path and fee levels) describing the swap path from Collateral Token to eth return Amount of eth returned to the user /
function _liquidateCollateralTokensForETH( address _collateralToken, uint256 _collateralRemaining, address _originalSender, uint256 _minAmountOutputToken, DEXAdapter.SwapData memory _swapData ) internal isValidPath(_swapData.path, _collateralToken, addresses.weth) returns(uint256)
function _liquidateCollateralTokensForETH( address _collateralToken, uint256 _collateralRemaining, address _originalSender, uint256 _minAmountOutputToken, DEXAdapter.SwapData memory _swapData ) internal isValidPath(_swapData.path, _collateralToken, addresses.weth) returns(uint256)
9,776
122
// Adjust the bonus effective stakee for user and whole userbase /
function adjustBoostedBalance(uint256 _boostedBalance) private { Balance storage balances = _balances[msg.sender]; uint256 previousBoostedBalance = balances.boostedBalance; if (_boostedBalance < previousBoostedBalance) { uint256 diffBalancesAccounting = previousBoostedBalance.sub(_boostedBalance); boostedTotalSupply = boostedTotalSupply.sub(diffBalancesAccounting); } else if (_boostedBalance > previousBoostedBalance) { uint256 diffBalancesAccounting = _boostedBalance.sub(previousBoostedBalance); boostedTotalSupply = boostedTotalSupply.add(diffBalancesAccounting); } balances.boostedBalance = _boostedBalance; }
function adjustBoostedBalance(uint256 _boostedBalance) private { Balance storage balances = _balances[msg.sender]; uint256 previousBoostedBalance = balances.boostedBalance; if (_boostedBalance < previousBoostedBalance) { uint256 diffBalancesAccounting = previousBoostedBalance.sub(_boostedBalance); boostedTotalSupply = boostedTotalSupply.sub(diffBalancesAccounting); } else if (_boostedBalance > previousBoostedBalance) { uint256 diffBalancesAccounting = _boostedBalance.sub(previousBoostedBalance); boostedTotalSupply = boostedTotalSupply.add(diffBalancesAccounting); } balances.boostedBalance = _boostedBalance; }
22,457
4
// Remove address' authorization. Owner only /
function unauthorize(address adr) public onlyOwner { authorizations[adr] = false; }
function unauthorize(address adr) public onlyOwner { authorizations[adr] = false; }
18,101
43
// to reward
_balances[_rewardPool] = add(_balances[_rewardPool],rewardFee); sendAmount = sub(sendAmount,rewardFee); _totalRewardToken = add(_totalRewardToken,rewardFee); emit Transfer(sender, _rewardPool, mul(rewardFee,2));
_balances[_rewardPool] = add(_balances[_rewardPool],rewardFee); sendAmount = sub(sendAmount,rewardFee); _totalRewardToken = add(_totalRewardToken,rewardFee); emit Transfer(sender, _rewardPool, mul(rewardFee,2));
16,864
583
// Add the managed token to the blacklist to disallow a token holder from executing actions on the token controller's (this contract) behalf
address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist);
address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist);
62,802
95
// We need to swap the current tokens to ETH and send to the charity wallet
swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToCharity(address(this).balance); }
swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToCharity(address(this).balance); }
37,017
88
// return current price of cToken in underlying /
function getPriceInToken() external view
function getPriceInToken() external view
2,964
6
// Function to withdraw link token /
function withdrawLink(uint256 _amount) external onlyOwner { LINK.transfer(msg.sender, _amount); }
function withdrawLink(uint256 _amount) external onlyOwner { LINK.transfer(msg.sender, _amount); }
39,137
168
// pool-related functions /
function poolLength() external view returns (uint256) { return _poolLength; }
function poolLength() external view returns (uint256) { return _poolLength; }
2,626
59
// Transfers the ownership of a child token ID to another address.Calculates child token ID using a namehash function.Requires the msg.sender to be the owner, approved, or operator of tokenId.Requires the token already exist. from current owner of the token to address to receive the ownership of the given token ID tokenId uint256 ID of the token to be transferred label subdomain label of the child token ID /
function transferFromChild(address from, address to, uint256 tokenId, string calldata label) external;
function transferFromChild(address from, address to, uint256 tokenId, string calldata label) external;
3,693
47
// Members must exist and be currently active to proclaim inactivity.
require(members_[_memberId].member); require(memberIsActive(_memberId));
require(members_[_memberId].member); require(memberIsActive(_memberId));
83,444
43
// Request document key retrieval.
function retrieveDocumentKeyShadow(bytes32 serverKeyId, bytes calldata requesterPublic) external payable;
function retrieveDocumentKeyShadow(bytes32 serverKeyId, bytes calldata requesterPublic) external payable;
41,949
2
// Bool
function getBool(bytes32 _key) public view returns (bool) { return boolStorage[_key]; }
function getBool(bytes32 _key) public view returns (bool) { return boolStorage[_key]; }
18,494
77
// user nonces for masterContract approvals
mapping(address => uint256) public nonces; bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
mapping(address => uint256) public nonces; bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
64,337
13
// Restore the orchestration from an isolated target
function restore(address target, address[] calldata contacts, bytes4[][] calldata permissions) external override auth
function restore(address target, address[] calldata contacts, bytes4[][] calldata permissions) external override auth
5,768
96
// if output is overweight, no fee, else fee
bool applyFee = outputVaultBalanceScaled < outputMaxWeight; uint256 maxInputUnits = clampedMax.divRatioPrecisely(data.input.ratio); uint256 outputUnitsIncFee = maxInputUnits.mulRatioTruncate(data.input.ratio).divRatioPrecisely(data.output.ratio); uint256 fee = applyFee ? data.mAsset.swapFee() : 0; uint256 outputFee = outputUnitsIncFee.mulTruncate(fee); return (true, "", maxInputUnits, outputUnitsIncFee.sub(outputFee));
bool applyFee = outputVaultBalanceScaled < outputMaxWeight; uint256 maxInputUnits = clampedMax.divRatioPrecisely(data.input.ratio); uint256 outputUnitsIncFee = maxInputUnits.mulRatioTruncate(data.input.ratio).divRatioPrecisely(data.output.ratio); uint256 fee = applyFee ? data.mAsset.swapFee() : 0; uint256 outputFee = outputUnitsIncFee.mulTruncate(fee); return (true, "", maxInputUnits, outputUnitsIncFee.sub(outputFee));
13,254
79
// Transfers the tokens to the receiver address. Transfers the tokens to the receiver address. _instaLoanVariables struct which includes list of token addresses and amounts. _receiver address to which tokens have to be transferred./
function safeTransfer( FlashloanVariables memory _instaLoanVariables, address _receiver
function safeTransfer( FlashloanVariables memory _instaLoanVariables, address _receiver
34,483
6
// END_OF_contract_SafeMath_________________________________________________________/ INTERFACES /
interface tokenRecipient { function receiveApproval(address _from, uint256 _tokenAmountApproved, address tokenMacroansy, bytes _extraData) public returns(bool success); }
interface tokenRecipient { function receiveApproval(address _from, uint256 _tokenAmountApproved, address tokenMacroansy, bytes _extraData) public returns(bool success); }
32,425
0
// Data needed to process onchain operation from block public data./Onchain operations is operations that need some processing on L1: Deposits, Withdrawals, ChangePubKey./ethWitness Some external data that can be needed for operation processing/publicDataOffset Byte offset in public data for onchain operation
struct OnchainOperationData { bytes ethWitness; uint32 publicDataOffset; }
struct OnchainOperationData { bytes ethWitness; uint32 publicDataOffset; }
32,675
285
// market manipulation prevention
require(tx.origin == msg.sender, "no smart contracts"); if (liquidityLoanCurrent == 0) { return; }
require(tx.origin == msg.sender, "no smart contracts"); if (liquidityLoanCurrent == 0) { return; }
12,799
5
// `msg.sender` approves `_addr` to spend `_value` tokens/_spender The address of the account able to transfer the tokens/_value The amount of wei to be approved for transfer/ return success Whether the approval was successful or not
function approve(address _spender, uint256 _value) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
27,268
3
// first skip first 32 bytes of signature
r := mload(add(sig, 32))
r := mload(add(sig, 32))
19,168
21
// Get the number of winnings of the user_better The address of the user /
function getBetterNumOfWinnings(address _better) public view returns(uint) { return betterNumWinning[_better]; }
function getBetterNumOfWinnings(address _better) public view returns(uint) { return betterNumWinning[_better]; }
4,952
40
// See {IERC20-transferFrom}. NOTE: Does not update the allowance if the current allowanceis the maximum `uint256`. Note that operator and allowance concepts are orthogonal: operators cannotcall `transferFrom` (unless they have allowance), and accounts withallowance cannot call `operatorSend` (unless they are operators). Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. /
function transferFrom( address holder, address recipient, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(holder, spender, amount); _send(holder, recipient, amount, "", "", false); return true; }
function transferFrom( address holder, address recipient, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(holder, spender, amount); _send(holder, recipient, amount, "", "", false); return true; }
6,264
8
// /Swaps msg.value of strikeTokens (ethers) to underlyingTokens./ Uses the strike ratio as the exchange rate. Strike ratio = base / quote./ Msg.value (quote units)base / quote = base units (underlyingTokens) to withdraw./This function is for options with WETH as the strike asset./ Burns option tokens, accepts ethers, and pushes out underlyingTokens./optionToken The address of the option contract./receiver The underlyingTokens are sent to the receiver address./
function safeExerciseWithETH( IWETH weth, IOption optionToken, address receiver
function safeExerciseWithETH( IWETH weth, IOption optionToken, address receiver
39,586
72
// A central config for the uAD system. Also acts as a central/ access control manager./For storing constants. For storing variables and allowing them to/ be changed by the admin (governance)/This should be used as a central access control manager which other/ contracts use to check permissions
contract UbiquityAlgorithmicDollarManager is AccessControl { using SafeERC20 for IERC20; bytes32 public constant UBQ_MINTER_ROLE = keccak256("UBQ_MINTER_ROLE"); bytes32 public constant UBQ_BURNER_ROLE = keccak256("UBQ_BURNER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant COUPON_MANAGER_ROLE = keccak256("COUPON_MANAGER"); bytes32 public constant BONDING_MANAGER_ROLE = keccak256("BONDING_MANAGER"); bytes32 public constant INCENTIVE_MANAGER_ROLE = keccak256("INCENTIVE_MANAGER"); bytes32 public constant UBQ_TOKEN_MANAGER_ROLE = keccak256("UBQ_TOKEN_MANAGER_ROLE"); address public twapOracleAddress; address public debtCouponAddress; address public dollarTokenAddress; // uAD address public couponCalculatorAddress; address public dollarMintingCalculatorAddress; address public bondingShareAddress; address public bondingContractAddress; address public stableSwapMetaPoolAddress; address public curve3PoolTokenAddress; // 3CRV address public treasuryAddress; address public governanceTokenAddress; // uGOV address public sushiSwapPoolAddress; // sushi pool uAD-uGOV address public masterChefAddress; address public formulasAddress; address public autoRedeemTokenAddress; // uAR address public uarCalculatorAddress; // uAR calculator //key = address of couponmanager, value = excessdollardistributor mapping(address => address) private _excessDollarDistributors; modifier onlyAdmin() { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "uADMGR: Caller is not admin" ); _; } constructor(address _admin) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(UBQ_MINTER_ROLE, _admin); _setupRole(PAUSER_ROLE, _admin); _setupRole(COUPON_MANAGER_ROLE, _admin); _setupRole(BONDING_MANAGER_ROLE, _admin); _setupRole(INCENTIVE_MANAGER_ROLE, _admin); _setupRole(UBQ_TOKEN_MANAGER_ROLE, address(this)); } // TODO Add a generic setter for extra addresses that needs to be linked function setTwapOracleAddress(address _twapOracleAddress) external onlyAdmin { twapOracleAddress = _twapOracleAddress; // to be removed TWAPOracle oracle = TWAPOracle(twapOracleAddress); oracle.update(); } function setuARTokenAddress(address _uarTokenAddress) external onlyAdmin { autoRedeemTokenAddress = _uarTokenAddress; } function setDebtCouponAddress(address _debtCouponAddress) external onlyAdmin { debtCouponAddress = _debtCouponAddress; } function setIncentiveToUAD(address _account, address _incentiveAddress) external onlyAdmin { IUbiquityAlgorithmicDollar(dollarTokenAddress).setIncentiveContract( _account, _incentiveAddress ); } function setDollarTokenAddress(address _dollarTokenAddress) external onlyAdmin { dollarTokenAddress = _dollarTokenAddress; } function setGovernanceTokenAddress(address _governanceTokenAddress) external onlyAdmin { governanceTokenAddress = _governanceTokenAddress; } function setSushiSwapPoolAddress(address _sushiSwapPoolAddress) external onlyAdmin { sushiSwapPoolAddress = _sushiSwapPoolAddress; } function setUARCalculatorAddress(address _uarCalculatorAddress) external onlyAdmin { uarCalculatorAddress = _uarCalculatorAddress; } function setCouponCalculatorAddress(address _couponCalculatorAddress) external onlyAdmin { couponCalculatorAddress = _couponCalculatorAddress; } function setDollarMintingCalculatorAddress( address _dollarMintingCalculatorAddress ) external onlyAdmin { dollarMintingCalculatorAddress = _dollarMintingCalculatorAddress; } function setExcessDollarsDistributor( address debtCouponManagerAddress, address excessCouponDistributor ) external onlyAdmin { _excessDollarDistributors[ debtCouponManagerAddress ] = excessCouponDistributor; } function setMasterChefAddress(address _masterChefAddress) external onlyAdmin { masterChefAddress = _masterChefAddress; } function setFormulasAddress(address _formulasAddress) external onlyAdmin { formulasAddress = _formulasAddress; } function setBondingShareAddress(address _bondingShareAddress) external onlyAdmin { bondingShareAddress = _bondingShareAddress; } function setStableSwapMetaPoolAddress(address _stableSwapMetaPoolAddress) external onlyAdmin { stableSwapMetaPoolAddress = _stableSwapMetaPoolAddress; } /** @notice set the bonding bontract smart contract address @dev bonding contract participants deposit curve LP token for a certain duration to earn uGOV and more curve LP token @param _bondingContractAddress bonding contract address */ function setBondingContractAddress(address _bondingContractAddress) external onlyAdmin { bondingContractAddress = _bondingContractAddress; } /** @notice set the treasury address @dev the treasury fund is used to maintain the protocol @param _treasuryAddress treasury fund address */ function setTreasuryAddress(address _treasuryAddress) external onlyAdmin { treasuryAddress = _treasuryAddress; } /** @notice deploy a new Curve metapools for uAD Token uAD/3Pool @dev From the curve documentation for uncollateralized algorithmic stablecoins amplification should be 5-10 @param _curveFactory MetaPool factory address @param _crvBasePool Address of the base pool to use within the new metapool. @param _crv3PoolTokenAddress curve 3Pool token Address @param _amplificationCoefficient amplification coefficient. The smaller it is the closer to a constant product we are. @param _fee Trade fee, given as an integer with 1e10 precision. */ function deployStableSwapPool( address _curveFactory, address _crvBasePool, address _crv3PoolTokenAddress, uint256 _amplificationCoefficient, uint256 _fee ) external onlyAdmin { // Create new StableSwap meta pool (uAD <-> 3Crv) address metaPool = ICurveFactory(_curveFactory).deploy_metapool( _crvBasePool, ERC20(dollarTokenAddress).name(), ERC20(dollarTokenAddress).symbol(), dollarTokenAddress, _amplificationCoefficient, _fee ); stableSwapMetaPoolAddress = metaPool; // Approve the newly-deployed meta pool to transfer this contract's funds uint256 crv3PoolTokenAmount = IERC20(_crv3PoolTokenAddress).balanceOf(address(this)); uint256 uADTokenAmount = IERC20(dollarTokenAddress).balanceOf(address(this)); // safe approve revert if approve from non-zero to non-zero allowance IERC20(_crv3PoolTokenAddress).safeApprove(metaPool, 0); IERC20(_crv3PoolTokenAddress).safeApprove( metaPool, crv3PoolTokenAmount ); IERC20(dollarTokenAddress).safeApprove(metaPool, 0); IERC20(dollarTokenAddress).safeApprove(metaPool, uADTokenAmount); // coin at index 0 is uAD and index 1 is 3CRV require( IMetaPool(metaPool).coins(0) == dollarTokenAddress && IMetaPool(metaPool).coins(1) == _crv3PoolTokenAddress, "uADMGR: COIN_ORDER_MISMATCH" ); // Add the initial liquidity to the StableSwap meta pool uint256[2] memory amounts = [ IERC20(dollarTokenAddress).balanceOf(address(this)), IERC20(_crv3PoolTokenAddress).balanceOf(address(this)) ]; // set curve 3Pool address curve3PoolTokenAddress = _crv3PoolTokenAddress; IMetaPool(metaPool).add_liquidity(amounts, 0, msg.sender); } function getExcessDollarsDistributor(address _debtCouponManagerAddress) external view returns (address) { return _excessDollarDistributors[_debtCouponManagerAddress]; } }
contract UbiquityAlgorithmicDollarManager is AccessControl { using SafeERC20 for IERC20; bytes32 public constant UBQ_MINTER_ROLE = keccak256("UBQ_MINTER_ROLE"); bytes32 public constant UBQ_BURNER_ROLE = keccak256("UBQ_BURNER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant COUPON_MANAGER_ROLE = keccak256("COUPON_MANAGER"); bytes32 public constant BONDING_MANAGER_ROLE = keccak256("BONDING_MANAGER"); bytes32 public constant INCENTIVE_MANAGER_ROLE = keccak256("INCENTIVE_MANAGER"); bytes32 public constant UBQ_TOKEN_MANAGER_ROLE = keccak256("UBQ_TOKEN_MANAGER_ROLE"); address public twapOracleAddress; address public debtCouponAddress; address public dollarTokenAddress; // uAD address public couponCalculatorAddress; address public dollarMintingCalculatorAddress; address public bondingShareAddress; address public bondingContractAddress; address public stableSwapMetaPoolAddress; address public curve3PoolTokenAddress; // 3CRV address public treasuryAddress; address public governanceTokenAddress; // uGOV address public sushiSwapPoolAddress; // sushi pool uAD-uGOV address public masterChefAddress; address public formulasAddress; address public autoRedeemTokenAddress; // uAR address public uarCalculatorAddress; // uAR calculator //key = address of couponmanager, value = excessdollardistributor mapping(address => address) private _excessDollarDistributors; modifier onlyAdmin() { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "uADMGR: Caller is not admin" ); _; } constructor(address _admin) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(UBQ_MINTER_ROLE, _admin); _setupRole(PAUSER_ROLE, _admin); _setupRole(COUPON_MANAGER_ROLE, _admin); _setupRole(BONDING_MANAGER_ROLE, _admin); _setupRole(INCENTIVE_MANAGER_ROLE, _admin); _setupRole(UBQ_TOKEN_MANAGER_ROLE, address(this)); } // TODO Add a generic setter for extra addresses that needs to be linked function setTwapOracleAddress(address _twapOracleAddress) external onlyAdmin { twapOracleAddress = _twapOracleAddress; // to be removed TWAPOracle oracle = TWAPOracle(twapOracleAddress); oracle.update(); } function setuARTokenAddress(address _uarTokenAddress) external onlyAdmin { autoRedeemTokenAddress = _uarTokenAddress; } function setDebtCouponAddress(address _debtCouponAddress) external onlyAdmin { debtCouponAddress = _debtCouponAddress; } function setIncentiveToUAD(address _account, address _incentiveAddress) external onlyAdmin { IUbiquityAlgorithmicDollar(dollarTokenAddress).setIncentiveContract( _account, _incentiveAddress ); } function setDollarTokenAddress(address _dollarTokenAddress) external onlyAdmin { dollarTokenAddress = _dollarTokenAddress; } function setGovernanceTokenAddress(address _governanceTokenAddress) external onlyAdmin { governanceTokenAddress = _governanceTokenAddress; } function setSushiSwapPoolAddress(address _sushiSwapPoolAddress) external onlyAdmin { sushiSwapPoolAddress = _sushiSwapPoolAddress; } function setUARCalculatorAddress(address _uarCalculatorAddress) external onlyAdmin { uarCalculatorAddress = _uarCalculatorAddress; } function setCouponCalculatorAddress(address _couponCalculatorAddress) external onlyAdmin { couponCalculatorAddress = _couponCalculatorAddress; } function setDollarMintingCalculatorAddress( address _dollarMintingCalculatorAddress ) external onlyAdmin { dollarMintingCalculatorAddress = _dollarMintingCalculatorAddress; } function setExcessDollarsDistributor( address debtCouponManagerAddress, address excessCouponDistributor ) external onlyAdmin { _excessDollarDistributors[ debtCouponManagerAddress ] = excessCouponDistributor; } function setMasterChefAddress(address _masterChefAddress) external onlyAdmin { masterChefAddress = _masterChefAddress; } function setFormulasAddress(address _formulasAddress) external onlyAdmin { formulasAddress = _formulasAddress; } function setBondingShareAddress(address _bondingShareAddress) external onlyAdmin { bondingShareAddress = _bondingShareAddress; } function setStableSwapMetaPoolAddress(address _stableSwapMetaPoolAddress) external onlyAdmin { stableSwapMetaPoolAddress = _stableSwapMetaPoolAddress; } /** @notice set the bonding bontract smart contract address @dev bonding contract participants deposit curve LP token for a certain duration to earn uGOV and more curve LP token @param _bondingContractAddress bonding contract address */ function setBondingContractAddress(address _bondingContractAddress) external onlyAdmin { bondingContractAddress = _bondingContractAddress; } /** @notice set the treasury address @dev the treasury fund is used to maintain the protocol @param _treasuryAddress treasury fund address */ function setTreasuryAddress(address _treasuryAddress) external onlyAdmin { treasuryAddress = _treasuryAddress; } /** @notice deploy a new Curve metapools for uAD Token uAD/3Pool @dev From the curve documentation for uncollateralized algorithmic stablecoins amplification should be 5-10 @param _curveFactory MetaPool factory address @param _crvBasePool Address of the base pool to use within the new metapool. @param _crv3PoolTokenAddress curve 3Pool token Address @param _amplificationCoefficient amplification coefficient. The smaller it is the closer to a constant product we are. @param _fee Trade fee, given as an integer with 1e10 precision. */ function deployStableSwapPool( address _curveFactory, address _crvBasePool, address _crv3PoolTokenAddress, uint256 _amplificationCoefficient, uint256 _fee ) external onlyAdmin { // Create new StableSwap meta pool (uAD <-> 3Crv) address metaPool = ICurveFactory(_curveFactory).deploy_metapool( _crvBasePool, ERC20(dollarTokenAddress).name(), ERC20(dollarTokenAddress).symbol(), dollarTokenAddress, _amplificationCoefficient, _fee ); stableSwapMetaPoolAddress = metaPool; // Approve the newly-deployed meta pool to transfer this contract's funds uint256 crv3PoolTokenAmount = IERC20(_crv3PoolTokenAddress).balanceOf(address(this)); uint256 uADTokenAmount = IERC20(dollarTokenAddress).balanceOf(address(this)); // safe approve revert if approve from non-zero to non-zero allowance IERC20(_crv3PoolTokenAddress).safeApprove(metaPool, 0); IERC20(_crv3PoolTokenAddress).safeApprove( metaPool, crv3PoolTokenAmount ); IERC20(dollarTokenAddress).safeApprove(metaPool, 0); IERC20(dollarTokenAddress).safeApprove(metaPool, uADTokenAmount); // coin at index 0 is uAD and index 1 is 3CRV require( IMetaPool(metaPool).coins(0) == dollarTokenAddress && IMetaPool(metaPool).coins(1) == _crv3PoolTokenAddress, "uADMGR: COIN_ORDER_MISMATCH" ); // Add the initial liquidity to the StableSwap meta pool uint256[2] memory amounts = [ IERC20(dollarTokenAddress).balanceOf(address(this)), IERC20(_crv3PoolTokenAddress).balanceOf(address(this)) ]; // set curve 3Pool address curve3PoolTokenAddress = _crv3PoolTokenAddress; IMetaPool(metaPool).add_liquidity(amounts, 0, msg.sender); } function getExcessDollarsDistributor(address _debtCouponManagerAddress) external view returns (address) { return _excessDollarDistributors[_debtCouponManagerAddress]; } }
51,587
38
// Set token data
_attributes[tokenIdToMint] = piglet;
_attributes[tokenIdToMint] = piglet;
28,251
127
// Generate canonical Nifty Gateway token representation. Nifty contracts have a data model called a 'niftyType' (typeCount) The 'niftyType' refers to a specific nifty in our contract, note that it gives no information about the edition size. In a given contract, 'niftyType' 1 could be an edition of 10, while 'niftyType' 2 is a 1/1, etc.
* The token IDs are encoded as follows: {id}{niftyType}{edition #} * 'niftyType' has 4 digits, and edition number does as well, to allow * for 9999 possible 'niftyType' and 9999 of each edition in each contract. * Example token id: [500010270] * This is from contract #5, it is 'niftyType' 1 in the contract, and it is * edition #270 of 'niftyType' 1. */ function _encodeTokenId(uint niftyType, uint tokenNumber) private view returns (uint) { return (topLevelMultiplier + (niftyType * midLevelMultiplier) + tokenNumber); }
* The token IDs are encoded as follows: {id}{niftyType}{edition #} * 'niftyType' has 4 digits, and edition number does as well, to allow * for 9999 possible 'niftyType' and 9999 of each edition in each contract. * Example token id: [500010270] * This is from contract #5, it is 'niftyType' 1 in the contract, and it is * edition #270 of 'niftyType' 1. */ function _encodeTokenId(uint niftyType, uint tokenNumber) private view returns (uint) { return (topLevelMultiplier + (niftyType * midLevelMultiplier) + tokenNumber); }
27,356
17
// Remove an account from the `liquidateByAMM` whitelist.keeperThe account of keeper. perpetualIndexThe index of perpetual in the liquidity pool /
function removeAMMKeeper(uint256 perpetualIndex, address keeper) external onlyOperatorOrGovernor
function removeAMMKeeper(uint256 perpetualIndex, address keeper) external onlyOperatorOrGovernor
4,678
6
// check msg.sender
require(_status >= 0 && _status <= uint(CommitmentStatus.verified));
require(_status >= 0 && _status <= uint(CommitmentStatus.verified));
48,699
15
// return "medicine_given";
return 1;
return 1;
15,993
55
// if next is zero node, _numTokens does not need to be greater
bool nextValid = (_numTokens <= getNumTokens(_voter, _nextID) || _nextID == 0); return prevValid && nextValid;
bool nextValid = (_numTokens <= getNumTokens(_voter, _nextID) || _nextID == 0); return prevValid && nextValid;
20,855
164
// Returns the value of excess collateral (in E18) held globally, compared to what is needed to maintain the global collateral ratio Also has throttling to avoid dumps during large price movements
function buybackAvailableCollat() public view returns (uint256) { uint256 total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); if (global_collateral_ratio > PRICE_PRECISION) global_collateral_ratio = PRICE_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(PRICE_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio if (global_collat_value > required_collat_dollar_value_d18) { // Get the theoretical buyback amount uint256 theoretical_bbk_amt = global_collat_value.sub(required_collat_dollar_value_d18); // See how much has collateral has been issued this hour uint256 current_hr_bbk = bbkHourlyCum[curEpochHr()]; // Account for the throttling return comboCalcBbkRct(current_hr_bbk, bbkMaxColE18OutPerHour, theoretical_bbk_amt); } else return 0; }
function buybackAvailableCollat() public view returns (uint256) { uint256 total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); if (global_collateral_ratio > PRICE_PRECISION) global_collateral_ratio = PRICE_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(PRICE_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio if (global_collat_value > required_collat_dollar_value_d18) { // Get the theoretical buyback amount uint256 theoretical_bbk_amt = global_collat_value.sub(required_collat_dollar_value_d18); // See how much has collateral has been issued this hour uint256 current_hr_bbk = bbkHourlyCum[curEpochHr()]; // Account for the throttling return comboCalcBbkRct(current_hr_bbk, bbkMaxColE18OutPerHour, theoretical_bbk_amt); } else return 0; }
16,301
68
// If there is no guest root, all users are invited
if (!invited && guestRoot == bytes32(0)) { invited = true; }
if (!invited && guestRoot == bytes32(0)) { invited = true; }
19,832
249
// This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.implement alternative mechanisms to perform token transfer, such as signature-based. Requirements: - `from` cannot be the zero address.- `to` cannot be the zero address.- `tokenId` token must exist and be owned by `from`.- If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. Emits a {Transfer} event. /
function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); if (to.isContract() && !_checkOnERC721Received(from, to, tokenId, _data) ) {
function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); if (to.isContract() && !_checkOnERC721Received(from, to, tokenId, _data) ) {
76,936
111
// ERC20 token case
return IERC20(token).balanceOf(address(this));
return IERC20(token).balanceOf(address(this));
44,525
61
// InitializableProductProxy Extends ProductProxy with an initializer for initializingfactory and init data. /
contract InitializableProductProxy is ProductProxy { /** * @dev Contract initializer. * @param factory_ Address of the initial factory. * @param data_ Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function __InitializableProductProxy_init(address factory_, bytes32 name_, bytes memory data_) public payable { require(_factory() == address(0)); assert(FACTORY_SLOT == bytes32(uint256(keccak256('eip1967.proxy.factory')) - 1)); assert(NAME_SLOT == bytes32(uint256(keccak256('eip1967.proxy.name')) - 1)); _setFactory(factory_); _setName(name_); if(data_.length > 0) { (bool success,) = _implementation().delegatecall(data_); require(success); } } }
contract InitializableProductProxy is ProductProxy { /** * @dev Contract initializer. * @param factory_ Address of the initial factory. * @param data_ Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function __InitializableProductProxy_init(address factory_, bytes32 name_, bytes memory data_) public payable { require(_factory() == address(0)); assert(FACTORY_SLOT == bytes32(uint256(keccak256('eip1967.proxy.factory')) - 1)); assert(NAME_SLOT == bytes32(uint256(keccak256('eip1967.proxy.name')) - 1)); _setFactory(factory_); _setName(name_); if(data_.length > 0) { (bool success,) = _implementation().delegatecall(data_); require(success); } } }
5,089
89
// The reward token
IERC20Metadata public rewardToken;
IERC20Metadata public rewardToken;
39,182
114
// Stores the value of live crowdsale time before the pause. Accumulates with multiple pauses.
uint256 internal pastCrowdsaleTime = 0;
uint256 internal pastCrowdsaleTime = 0;
27,819
43
// ERROR CODES /
struct LockedDeposits { uint counter; mapping(uint => uint) index2Date; mapping(uint => uint) date2deposit; }
struct LockedDeposits { uint counter; mapping(uint => uint) index2Date; mapping(uint => uint) date2deposit; }
14,869
3
// Emitted on Bonfire burnDiceOnly call.
event BonfireBurnDiceOnly( address indexed mintedTo, uint256[] indexed burntDiceIDs );
event BonfireBurnDiceOnly( address indexed mintedTo, uint256[] indexed burntDiceIDs );
11,041
9
// Set if words are locked /
function lockWords(bool locked) external;
function lockWords(bool locked) external;
43,620
32
// Forward deposit to RP & get amount of Reth minted
uint256 rethBalance1 = RocketTokenRETHInterface(rocketTokenRETHAddress).balanceOf(address(this));
uint256 rethBalance1 = RocketTokenRETHInterface(rocketTokenRETHAddress).balanceOf(address(this));
19,473
5
// retrieve the size of the code, this needs assembly
let size := extcodesize(_addr)
let size := extcodesize(_addr)
8,096