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
36
// only check if target is a contract if the call was successful and the return data is empty otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) { revert AddressEmptyCode(target); }
if (returndata.length == 0 && target.code.length == 0) { revert AddressEmptyCode(target); }
8,693
15
// Safe math functions will throw if value invalid
balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true;
balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true;
39,568
0
// KYBER NETWORK INTERFACE FUNCTIONS/
function getExpectedRate( ERC20 src, ERC20 dest, uint srcQty ) public view returns (uint expectedRate, uint slippageRate)
function getExpectedRate( ERC20 src, ERC20 dest, uint srcQty ) public view returns (uint expectedRate, uint slippageRate)
13,738
62
// Event for deposits
event DepositERC( address indexed sender, string tokenName, address tokenAddress, uint256 amount, string cardanoAddress ); event FeeConfigUpdated(address indexed user, uint256 feeAmount, address feeAddr);
event DepositERC( address indexed sender, string tokenName, address tokenAddress, uint256 amount, string cardanoAddress ); event FeeConfigUpdated(address indexed user, uint256 feeAmount, address feeAddr);
46,901
1
// Exclusive sales mechanism for Keep it Heady using Zora V3 Module (Asks V1.1)
function listForSale() public { _createAsk(tokenId); }
function listForSale() public { _createAsk(tokenId); }
9,337
23
// Emit a global event when a new loan request is created.
function logRequestLoan(uint256 reqID_) external onlyFromFactory { emit RequestLoan(msg.sender, address(Cooler(msg.sender).collateral()), address(Cooler(msg.sender).debt()), reqID_); }
function logRequestLoan(uint256 reqID_) external onlyFromFactory { emit RequestLoan(msg.sender, address(Cooler(msg.sender).collateral()), address(Cooler(msg.sender).debt()), reqID_); }
34,459
0
// Refund only if name/adddress not in blacklist add require here after o/p of ML algorithm is obtained
account['Harishchandra'] = 0x2f860BF52aF0B67B3EC511027A95cA663c0C841B; uint refund = totalDeposits[newsArticlesPublished].amountPayed;
account['Harishchandra'] = 0x2f860BF52aF0B67B3EC511027A95cA663c0C841B; uint refund = totalDeposits[newsArticlesPublished].amountPayed;
1,934
102
// Perform LP token migration from legacy UniswapV2 to PowerSwap. Take the current LP token address and return the new LP token address. Migrator should have full access to the caller's LP token. Return the new LP token address. XXX Migrator must have allowance access to UniswapV2 LP tokens. PowerSwap must mint EXACTLY the same amount of PowerSwap LP tokens or else something bad will happen. Traditional UniswapV2 does not do that so be careful!
function migrate(IERC20 token, uint8 poolType) external returns (IERC20);
function migrate(IERC20 token, uint8 poolType) external returns (IERC20);
30,780
14
// Counter of all minted tokens available for sale /
uint256 public totalResourcesForSale;
uint256 public totalResourcesForSale;
16,022
14
// id for the first user is 0
assertEq(six, bytes32(uint256(1)));
assertEq(six, bytes32(uint256(1)));
53,999
82
// Remove fees for transfers to and from charity account or to excluded account
bool takeFee = true; if (_isCharity[sender] || _isCharity[recipient] || _isExcluded[recipient]) { takeFee = false; }
bool takeFee = true; if (_isCharity[sender] || _isCharity[recipient] || _isExcluded[recipient]) { takeFee = false; }
37,179
44
// Constructor _owner The account which controls this contract. /
constructor(address _owner) Owned(_owner) public
constructor(address _owner) Owned(_owner) public
15,351
19
// Overload of {ECDSA-tryRecover} that receives the `v`,`r` and `s` signature fields separately. _Available since v4.3._ /
function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) {
function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) {
5,304
85
// yfi.mint(address(this),initreward);
rewardRate = initreward.div(DURATION); periodFinish = block.timestamp.add(DURATION); emit RewardAdded(initreward);
rewardRate = initreward.div(DURATION); periodFinish = block.timestamp.add(DURATION); emit RewardAdded(initreward);
40,157
68
// Main contract that acts as a central component registry for the protocol./ The kernel manages modules and policies. The kernel is mutated via predefined Actions,/ which are input from any address assigned as the executor. The executor can be changed as needed.
contract Kernel { // ========= EVENTS ========= // event PermissionsUpdated( Keycode indexed keycode_, Policy indexed policy_, bytes4 funcSelector_, bool granted_ ); event ActionExecuted(Actions indexed action_, address indexed target_); // ========= ERRORS ========= // error Kernel_OnlyExecutor(address caller_); error Kernel_ModuleAlreadyInstalled(Keycode module_); error Kernel_InvalidModuleUpgrade(Keycode module_); error Kernel_PolicyAlreadyActivated(address policy_); error Kernel_PolicyNotActivated(address policy_); // ========= PRIVILEGED ADDRESSES ========= // /// @notice Address that is able to initiate Actions in the kernel. Can be assigned to a multisig or governance contract. address public executor; // ========= MODULE MANAGEMENT ========= // /// @notice Array of all modules currently installed. Keycode[] public allKeycodes; /// @notice Mapping of module address to keycode. mapping(Keycode => Module) public getModuleForKeycode; /// @notice Mapping of keycode to module address. mapping(Module => Keycode) public getKeycodeForModule; /// @notice Mapping of a keycode to all of its policy dependents. Used to efficiently reconfigure policy dependencies. mapping(Keycode => Policy[]) public moduleDependents; /// @notice Helper for module dependent arrays. Prevents the need to loop through array. mapping(Keycode => mapping(Policy => uint256)) public getDependentIndex; /// @notice Module <> Policy Permissions. /// @dev Keycode -> Policy -> Function Selector -> bool for permission mapping(Keycode => mapping(Policy => mapping(bytes4 => bool))) public modulePermissions; // ========= POLICY MANAGEMENT ========= // /// @notice List of all active policies Policy[] public activePolicies; /// @notice Helper to get active policy quickly. Prevents need to loop through array. mapping(Policy => uint256) public getPolicyIndex; //============================================================================================// // CORE FUNCTIONS // //============================================================================================// constructor() { executor = msg.sender; } /// @notice Modifier to check if caller is the executor. modifier onlyExecutor() { if (msg.sender != executor) revert Kernel_OnlyExecutor(msg.sender); _; } function isPolicyActive(Policy policy_) public view returns (bool) { return activePolicies.length > 0 && activePolicies[getPolicyIndex[policy_]] == policy_; } /// @notice Main kernel function. Initiates state changes to kernel depending on Action passed in. function executeAction(Actions action_, address target_) external onlyExecutor { if (action_ == Actions.InstallModule) { ensureContract(target_); ensureValidKeycode(Module(target_).KEYCODE()); _installModule(Module(target_)); } else if (action_ == Actions.UpgradeModule) { ensureContract(target_); ensureValidKeycode(Module(target_).KEYCODE()); _upgradeModule(Module(target_)); } else if (action_ == Actions.ActivatePolicy) { ensureContract(target_); _activatePolicy(Policy(target_)); } else if (action_ == Actions.DeactivatePolicy) { ensureContract(target_); _deactivatePolicy(Policy(target_)); } else if (action_ == Actions.ChangeExecutor) { executor = target_; } else if (action_ == Actions.MigrateKernel) { ensureContract(target_); _migrateKernel(Kernel(target_)); } emit ActionExecuted(action_, target_); } function _installModule(Module newModule_) internal { Keycode keycode = newModule_.KEYCODE(); if (address(getModuleForKeycode[keycode]) != address(0)) revert Kernel_ModuleAlreadyInstalled(keycode); getModuleForKeycode[keycode] = newModule_; getKeycodeForModule[newModule_] = keycode; allKeycodes.push(keycode); newModule_.INIT(); } function _upgradeModule(Module newModule_) internal { Keycode keycode = newModule_.KEYCODE(); Module oldModule = getModuleForKeycode[keycode]; if (address(oldModule) == address(0) || oldModule == newModule_) revert Kernel_InvalidModuleUpgrade(keycode); getKeycodeForModule[oldModule] = Keycode.wrap(bytes5(0)); getKeycodeForModule[newModule_] = keycode; getModuleForKeycode[keycode] = newModule_; newModule_.INIT(); _reconfigurePolicies(keycode); } function _activatePolicy(Policy policy_) internal { if (isPolicyActive(policy_)) revert Kernel_PolicyAlreadyActivated(address(policy_)); // Add policy to list of active policies activePolicies.push(policy_); getPolicyIndex[policy_] = activePolicies.length - 1; // Record module dependencies Keycode[] memory dependencies = policy_.configureDependencies(); uint256 depLength = dependencies.length; for (uint256 i; i < depLength; ) { Keycode keycode = dependencies[i]; moduleDependents[keycode].push(policy_); getDependentIndex[keycode][policy_] = moduleDependents[keycode].length - 1; unchecked { ++i; } } // Grant permissions for policy to access restricted module functions Permissions[] memory requests = policy_.requestPermissions(); _setPolicyPermissions(policy_, requests, true); } function _deactivatePolicy(Policy policy_) internal { if (!isPolicyActive(policy_)) revert Kernel_PolicyNotActivated(address(policy_)); // Revoke permissions Permissions[] memory requests = policy_.requestPermissions(); _setPolicyPermissions(policy_, requests, false); // Remove policy from all policy data structures uint256 idx = getPolicyIndex[policy_]; Policy lastPolicy = activePolicies[activePolicies.length - 1]; activePolicies[idx] = lastPolicy; activePolicies.pop(); getPolicyIndex[lastPolicy] = idx; delete getPolicyIndex[policy_]; // Remove policy from module dependents _pruneFromDependents(policy_); } /// @notice All functionality will move to the new kernel. WARNING: ACTION WILL BRICK THIS KERNEL. /// @dev New kernel must add in all of the modules and policies via executeAction. /// @dev NOTE: Data does not get cleared from this kernel. function _migrateKernel(Kernel newKernel_) internal { uint256 keycodeLen = allKeycodes.length; for (uint256 i; i < keycodeLen; ) { Module module = Module(getModuleForKeycode[allKeycodes[i]]); module.changeKernel(newKernel_); unchecked { ++i; } } uint256 policiesLen = activePolicies.length; for (uint256 j; j < policiesLen; ) { Policy policy = activePolicies[j]; // Deactivate before changing kernel policy.changeKernel(newKernel_); unchecked { ++j; } } } function _reconfigurePolicies(Keycode keycode_) internal { Policy[] memory dependents = moduleDependents[keycode_]; uint256 depLength = dependents.length; for (uint256 i; i < depLength; ) { dependents[i].configureDependencies(); unchecked { ++i; } } } function _setPolicyPermissions( Policy policy_, Permissions[] memory requests_, bool grant_ ) internal { uint256 reqLength = requests_.length; for (uint256 i = 0; i < reqLength; ) { Permissions memory request = requests_[i]; modulePermissions[request.keycode][policy_][request.funcSelector] = grant_; emit PermissionsUpdated(request.keycode, policy_, request.funcSelector, grant_); unchecked { ++i; } } } function _pruneFromDependents(Policy policy_) internal { Keycode[] memory dependencies = policy_.configureDependencies(); uint256 depcLength = dependencies.length; for (uint256 i; i < depcLength; ) { Keycode keycode = dependencies[i]; Policy[] storage dependents = moduleDependents[keycode]; uint256 origIndex = getDependentIndex[keycode][policy_]; Policy lastPolicy = dependents[dependents.length - 1]; // Swap with last and pop dependents[origIndex] = lastPolicy; dependents.pop(); // Record new index and delete deactivated policy index getDependentIndex[keycode][lastPolicy] = origIndex; delete getDependentIndex[keycode][policy_]; unchecked { ++i; } } } }
contract Kernel { // ========= EVENTS ========= // event PermissionsUpdated( Keycode indexed keycode_, Policy indexed policy_, bytes4 funcSelector_, bool granted_ ); event ActionExecuted(Actions indexed action_, address indexed target_); // ========= ERRORS ========= // error Kernel_OnlyExecutor(address caller_); error Kernel_ModuleAlreadyInstalled(Keycode module_); error Kernel_InvalidModuleUpgrade(Keycode module_); error Kernel_PolicyAlreadyActivated(address policy_); error Kernel_PolicyNotActivated(address policy_); // ========= PRIVILEGED ADDRESSES ========= // /// @notice Address that is able to initiate Actions in the kernel. Can be assigned to a multisig or governance contract. address public executor; // ========= MODULE MANAGEMENT ========= // /// @notice Array of all modules currently installed. Keycode[] public allKeycodes; /// @notice Mapping of module address to keycode. mapping(Keycode => Module) public getModuleForKeycode; /// @notice Mapping of keycode to module address. mapping(Module => Keycode) public getKeycodeForModule; /// @notice Mapping of a keycode to all of its policy dependents. Used to efficiently reconfigure policy dependencies. mapping(Keycode => Policy[]) public moduleDependents; /// @notice Helper for module dependent arrays. Prevents the need to loop through array. mapping(Keycode => mapping(Policy => uint256)) public getDependentIndex; /// @notice Module <> Policy Permissions. /// @dev Keycode -> Policy -> Function Selector -> bool for permission mapping(Keycode => mapping(Policy => mapping(bytes4 => bool))) public modulePermissions; // ========= POLICY MANAGEMENT ========= // /// @notice List of all active policies Policy[] public activePolicies; /// @notice Helper to get active policy quickly. Prevents need to loop through array. mapping(Policy => uint256) public getPolicyIndex; //============================================================================================// // CORE FUNCTIONS // //============================================================================================// constructor() { executor = msg.sender; } /// @notice Modifier to check if caller is the executor. modifier onlyExecutor() { if (msg.sender != executor) revert Kernel_OnlyExecutor(msg.sender); _; } function isPolicyActive(Policy policy_) public view returns (bool) { return activePolicies.length > 0 && activePolicies[getPolicyIndex[policy_]] == policy_; } /// @notice Main kernel function. Initiates state changes to kernel depending on Action passed in. function executeAction(Actions action_, address target_) external onlyExecutor { if (action_ == Actions.InstallModule) { ensureContract(target_); ensureValidKeycode(Module(target_).KEYCODE()); _installModule(Module(target_)); } else if (action_ == Actions.UpgradeModule) { ensureContract(target_); ensureValidKeycode(Module(target_).KEYCODE()); _upgradeModule(Module(target_)); } else if (action_ == Actions.ActivatePolicy) { ensureContract(target_); _activatePolicy(Policy(target_)); } else if (action_ == Actions.DeactivatePolicy) { ensureContract(target_); _deactivatePolicy(Policy(target_)); } else if (action_ == Actions.ChangeExecutor) { executor = target_; } else if (action_ == Actions.MigrateKernel) { ensureContract(target_); _migrateKernel(Kernel(target_)); } emit ActionExecuted(action_, target_); } function _installModule(Module newModule_) internal { Keycode keycode = newModule_.KEYCODE(); if (address(getModuleForKeycode[keycode]) != address(0)) revert Kernel_ModuleAlreadyInstalled(keycode); getModuleForKeycode[keycode] = newModule_; getKeycodeForModule[newModule_] = keycode; allKeycodes.push(keycode); newModule_.INIT(); } function _upgradeModule(Module newModule_) internal { Keycode keycode = newModule_.KEYCODE(); Module oldModule = getModuleForKeycode[keycode]; if (address(oldModule) == address(0) || oldModule == newModule_) revert Kernel_InvalidModuleUpgrade(keycode); getKeycodeForModule[oldModule] = Keycode.wrap(bytes5(0)); getKeycodeForModule[newModule_] = keycode; getModuleForKeycode[keycode] = newModule_; newModule_.INIT(); _reconfigurePolicies(keycode); } function _activatePolicy(Policy policy_) internal { if (isPolicyActive(policy_)) revert Kernel_PolicyAlreadyActivated(address(policy_)); // Add policy to list of active policies activePolicies.push(policy_); getPolicyIndex[policy_] = activePolicies.length - 1; // Record module dependencies Keycode[] memory dependencies = policy_.configureDependencies(); uint256 depLength = dependencies.length; for (uint256 i; i < depLength; ) { Keycode keycode = dependencies[i]; moduleDependents[keycode].push(policy_); getDependentIndex[keycode][policy_] = moduleDependents[keycode].length - 1; unchecked { ++i; } } // Grant permissions for policy to access restricted module functions Permissions[] memory requests = policy_.requestPermissions(); _setPolicyPermissions(policy_, requests, true); } function _deactivatePolicy(Policy policy_) internal { if (!isPolicyActive(policy_)) revert Kernel_PolicyNotActivated(address(policy_)); // Revoke permissions Permissions[] memory requests = policy_.requestPermissions(); _setPolicyPermissions(policy_, requests, false); // Remove policy from all policy data structures uint256 idx = getPolicyIndex[policy_]; Policy lastPolicy = activePolicies[activePolicies.length - 1]; activePolicies[idx] = lastPolicy; activePolicies.pop(); getPolicyIndex[lastPolicy] = idx; delete getPolicyIndex[policy_]; // Remove policy from module dependents _pruneFromDependents(policy_); } /// @notice All functionality will move to the new kernel. WARNING: ACTION WILL BRICK THIS KERNEL. /// @dev New kernel must add in all of the modules and policies via executeAction. /// @dev NOTE: Data does not get cleared from this kernel. function _migrateKernel(Kernel newKernel_) internal { uint256 keycodeLen = allKeycodes.length; for (uint256 i; i < keycodeLen; ) { Module module = Module(getModuleForKeycode[allKeycodes[i]]); module.changeKernel(newKernel_); unchecked { ++i; } } uint256 policiesLen = activePolicies.length; for (uint256 j; j < policiesLen; ) { Policy policy = activePolicies[j]; // Deactivate before changing kernel policy.changeKernel(newKernel_); unchecked { ++j; } } } function _reconfigurePolicies(Keycode keycode_) internal { Policy[] memory dependents = moduleDependents[keycode_]; uint256 depLength = dependents.length; for (uint256 i; i < depLength; ) { dependents[i].configureDependencies(); unchecked { ++i; } } } function _setPolicyPermissions( Policy policy_, Permissions[] memory requests_, bool grant_ ) internal { uint256 reqLength = requests_.length; for (uint256 i = 0; i < reqLength; ) { Permissions memory request = requests_[i]; modulePermissions[request.keycode][policy_][request.funcSelector] = grant_; emit PermissionsUpdated(request.keycode, policy_, request.funcSelector, grant_); unchecked { ++i; } } } function _pruneFromDependents(Policy policy_) internal { Keycode[] memory dependencies = policy_.configureDependencies(); uint256 depcLength = dependencies.length; for (uint256 i; i < depcLength; ) { Keycode keycode = dependencies[i]; Policy[] storage dependents = moduleDependents[keycode]; uint256 origIndex = getDependentIndex[keycode][policy_]; Policy lastPolicy = dependents[dependents.length - 1]; // Swap with last and pop dependents[origIndex] = lastPolicy; dependents.pop(); // Record new index and delete deactivated policy index getDependentIndex[keycode][lastPolicy] = origIndex; delete getDependentIndex[keycode][policy_]; unchecked { ++i; } } } }
24,726
18
// Returns a recipient's percent share in basis points. index The index of the recipient to get the share of.return percentInBasisPoints The percent of the payment received by the recipient, in basis points. /
function getPercentInBasisPointsByIndex(uint256 index) external view returns (uint256 percentInBasisPoints) { percentInBasisPoints = _shares[index].percentInBasisPoints; }
function getPercentInBasisPointsByIndex(uint256 index) external view returns (uint256 percentInBasisPoints) { percentInBasisPoints = _shares[index].percentInBasisPoints; }
20,192
93
// Creates an escape hatch function that can be called in an/emergency that will allow designated addresses to send any ether or tokens/held in the contract to an `escapeHatchDestination`
contract Escapable is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; /// @notice The `escapeHatch()` should only be called as a last resort if a /// security issue is uncovered or something unexpected happened /// @param _token to transfer, use 0x0 for ether function escapeHatch(address _token, address payable _escapeHatchDestination) external onlyOwner nonReentrant { require(_escapeHatchDestination != address(0x0)); uint256 balance; /// @dev Logic for ether if (_token == address(0x0)) { balance = address(this).balance; _escapeHatchDestination.transfer(balance); EscapeHatchCalled(_token, balance); return; } // Logic for tokens IERC20 token = IERC20(_token); balance = token.balanceOf(address(this)); token.safeTransfer(_escapeHatchDestination, balance); emit EscapeHatchCalled(_token, balance); } event EscapeHatchCalled(address token, uint256 amount); }
contract Escapable is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; /// @notice The `escapeHatch()` should only be called as a last resort if a /// security issue is uncovered or something unexpected happened /// @param _token to transfer, use 0x0 for ether function escapeHatch(address _token, address payable _escapeHatchDestination) external onlyOwner nonReentrant { require(_escapeHatchDestination != address(0x0)); uint256 balance; /// @dev Logic for ether if (_token == address(0x0)) { balance = address(this).balance; _escapeHatchDestination.transfer(balance); EscapeHatchCalled(_token, balance); return; } // Logic for tokens IERC20 token = IERC20(_token); balance = token.balanceOf(address(this)); token.safeTransfer(_escapeHatchDestination, balance); emit EscapeHatchCalled(_token, balance); } event EscapeHatchCalled(address token, uint256 amount); }
19,060
7
// Emitted when the trusted organization is added.
event TrustedOrganizationsAdded(TrustedOrganization[] orgs);
event TrustedOrganizationsAdded(TrustedOrganization[] orgs);
24,010
43
// pair1=_pair1;(uint112 _reserve0, uint112 _reserve1, ) = IUniswapV2Pair(_pair1).getReserves();
IUniswapV2Pair(_pair1).swap(amount1, amount1a, address(this), "");
IUniswapV2Pair(_pair1).swap(amount1, amount1a, address(this), "");
1,019
36
// Used to mint a batch of currency at once.This gives us a maximum of 2^96 tokens per user.Expected packed structure is [ADDR(20) | VALUE(12)].nonce The minting nonce, an incorrect nonce is rejected. bitsAn array of packed bytes of address, value mappings./
function multiMint(uint nonce, uint256[] bits) onlyOwner { require(!mintingStopped); if (nonce != mintingNonce) return; mintingNonce += 1; uint256 lomask = (1 << 96) - 1; uint created = 0; for (uint i=0; i<bits.length; i++) { address a = address(bits[i]>>96); uint value = bits[i]&lomask; balanceOf[a] = balanceOf[a] + value; controller.ledgerTransfer(0, a, value); created += value; } totalSupply += created; }
function multiMint(uint nonce, uint256[] bits) onlyOwner { require(!mintingStopped); if (nonce != mintingNonce) return; mintingNonce += 1; uint256 lomask = (1 << 96) - 1; uint created = 0; for (uint i=0; i<bits.length; i++) { address a = address(bits[i]>>96); uint value = bits[i]&lomask; balanceOf[a] = balanceOf[a] + value; controller.ledgerTransfer(0, a, value); created += value; } totalSupply += created; }
32,011
73
// Updates `owner` s allowance for `spender` based on spent `amount`. Does not update the allowance amount in case of infinite allowance.Revert if not enough allowance is available.
* Might emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); _approve(owner, spender, currentAllowance.sub(amount)); } }
* Might emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); _approve(owner, spender, currentAllowance.sub(amount)); } }
34,686
97
// transfer connectors remains to fund and calculate how much connectors was spended (current - remains)
connectorsSpended = _transferPoolConnectorsRemains( _connectorsAddress, _connectorsAmount);
connectorsSpended = _transferPoolConnectorsRemains( _connectorsAddress, _connectorsAmount);
33,122
78
// Update slope and timestamp
_lastPoint.slope = _lastPoint.slope + _slopeDelta; _lastPoint.timestamp = _weekCursor;
_lastPoint.slope = _lastPoint.slope + _slopeDelta; _lastPoint.timestamp = _weekCursor;
41,400
28
// update registrar registrar new registrar /
function setRegistrar(address registrar) external onlyOwnerOrRegistrar { address previous = s_registrar; require(registrar != previous, "Same registrar"); s_registrar = registrar; emit RegistrarChanged(previous, registrar); }
function setRegistrar(address registrar) external onlyOwnerOrRegistrar { address previous = s_registrar; require(registrar != previous, "Same registrar"); s_registrar = registrar; emit RegistrarChanged(previous, registrar); }
20,309
35
// Invalid version as defined by connector
if (newVersion == 0) return error('Invalid version, Wallet.updateLogic()'); logic_ = newVersion; return true;
if (newVersion == 0) return error('Invalid version, Wallet.updateLogic()'); logic_ = newVersion; return true;
20,038
11
// Get Reserves
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
47,065
210
// INTERNAL /
{ if (enhancement >= 5) { adjustment = enhancement - 4; } }
{ if (enhancement >= 5) { adjustment = enhancement - 4; } }
45,986
109
// Burns the coins held by the sender./ _value The amount of coins to burn./ This function is overridden to leverage Pausable feature.
function burn(uint256 _value) public revertIfLocked(msg.sender)
function burn(uint256 _value) public revertIfLocked(msg.sender)
49,622
54
// Removes all options from the blankOptions array. Iterates through the blankOptions array and removes each element. /
function emptyBlankOptions() external onlyOwner { uint256 blankOptionsLen = blankOptions.length; for (uint8 i = 0; i < blankOptionsLen; i++) { blankOptions.pop(); } blankOptionCount = 0; }
function emptyBlankOptions() external onlyOwner { uint256 blankOptionsLen = blankOptions.length; for (uint8 i = 0; i < blankOptionsLen; i++) { blankOptions.pop(); } blankOptionCount = 0; }
25,689
65
// the all dealers share the dealer reward.
uint256 _fee = _dealerPotDelta; for (_i = 0; _i < dealers.length; ++_i) { if (dealers[_i] == address(0)) { break; }
uint256 _fee = _dealerPotDelta; for (_i = 0; _i < dealers.length; ++_i) { if (dealers[_i] == address(0)) { break; }
36,568
20
// timestamp at which votes close. /
function proposalDeadline(uint256 proposalId) public view returns (uint256)
function proposalDeadline(uint256 proposalId) public view returns (uint256)
24,856
187
// Draw collateral to repay the flash loan
drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount));
drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount));
39,940
382
// round 41
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006) 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, 2558302139544901035700544058046419714227464650146159803703499681139469546006) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
9,288
46
// @Dev can transfer onlyDev functions to another address
function TransferDeveloper(address _nextDev) public onlyDev { devAddress = _nextDev; emit DevAddressChanged(devAddress); }
function TransferDeveloper(address _nextDev) public onlyDev { devAddress = _nextDev; emit DevAddressChanged(devAddress); }
12,330
17
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } }
function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } }
8,959
13
// initialize the result
result = (_amountIn * rate) / decimals; oldestRateTimestamp = timestamp;
result = (_amountIn * rate) / decimals; oldestRateTimestamp = timestamp;
30,448
89
// Option to set fee or no fee for transfer (just in case the no fee transfer option is exploited in future!) True = there will be no fees when moving tokens around or giving them to friends! (There will only be a fee to buy or sell) False = there will be a fee when buying/selling/tranfering tokens Default is true
function set_Transfers_Without_Fees(bool true_or_false) external onlyOwner { noFeeToTransfer = true_or_false; }
function set_Transfers_Without_Fees(bool true_or_false) external onlyOwner { noFeeToTransfer = true_or_false; }
12,977
118
// for vesting
uint256 lastUpdatedBlock; bool needVesting;
uint256 lastUpdatedBlock; bool needVesting;
29,382
6
// See {IERC721Enumerable-tokenOfOwnerByIndex}./
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); uint256 tokenId = _ownedTokens[owner][index];
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); uint256 tokenId = _ownedTokens[owner][index];
12,852
220
// 2. Check price channel
address ntokenAddress = _getNTokenAddress(tokenAddress); require(ntokenAddress != address(0) && ntokenAddress != tokenAddress, "NM:!tokenAddress");
address ntokenAddress = _getNTokenAddress(tokenAddress); require(ntokenAddress != address(0) && ntokenAddress != tokenAddress, "NM:!tokenAddress");
12,626
77
// Muldiv operation overflow. /
error MathOverflowedMulDiv();
error MathOverflowedMulDiv();
22,630
119
// Gets the Total Sum Assured amount of a given currency and smart contract address.
function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns (uint amount) { amount = currencyCSAOfSCAdd[_add][_curr]; }
function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns (uint amount) { amount = currencyCSAOfSCAdd[_add][_curr]; }
34,598
15
// To store information about raw material supplier
struct rawMaterialSupplier { address addr; uint256 id; //supplier id string name; //Name of the raw material supplier string place; //Place the raw material supplier is based in }
struct rawMaterialSupplier { address addr; uint256 id; //supplier id string name; //Name of the raw material supplier string place; //Place the raw material supplier is based in }
896
11
// Check if it has enough balance to set the value
if (value < newValue) throw; value = newValue;
if (value < newValue) throw; value = newValue;
5,420
27
// Get the nested dynamic data from calldata. _offset The dynamic offset of the nested calldata _nestedOffset The offset within the nested calldata, exclusive of the selector /
function getNestedCallData(uint256 _offset, uint256 _nestedOffset) internal pure returns (bytes memory data) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := calldataload(add(_offset, _nestedOffset)) let len := add(32, calldataload(add(4, add(_offset, ptr)))) data := mload(0x40) calldatacopy(data, add(add(4, _offset), ptr), len) mstore(0x40, add(data, len)) } }
function getNestedCallData(uint256 _offset, uint256 _nestedOffset) internal pure returns (bytes memory data) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := calldataload(add(_offset, _nestedOffset)) let len := add(32, calldataload(add(4, add(_offset, ptr)))) data := mload(0x40) calldatacopy(data, add(add(4, _offset), ptr), len) mstore(0x40, add(data, len)) } }
20,175
47
// get the release of the multiplier balance.--------------------------------------------- user --> the address of the user.---------------------------------------returns the release timestamp. /
function getUserRelease(address user) internal view returns (uint256) { return _users[user].release; }
function getUserRelease(address user) internal view returns (uint256) { return _users[user].release; }
28,525
45
// Address where funds are collected
address public wallet1 = 0x56E4e5d451dF045827e214FE10bBF99D730d9683; address public wallet2 = 0x8C0988711E60CfF153359Ab6CFC8d45565C6ce79; address public wallet3 = 0x0EdF5c34ddE2573f162CcfEede99EeC6aCF1c2CB; address public wallet4 = 0xcBdC5eE000f77f3bCc0eFeF0dc47d38911CBD45B;
address public wallet1 = 0x56E4e5d451dF045827e214FE10bBF99D730d9683; address public wallet2 = 0x8C0988711E60CfF153359Ab6CFC8d45565C6ce79; address public wallet3 = 0x0EdF5c34ddE2573f162CcfEede99EeC6aCF1c2CB; address public wallet4 = 0xcBdC5eE000f77f3bCc0eFeF0dc47d38911CBD45B;
24,601
7
// PAYOUT /
function withdraw() public nonReentrant { uint256 balance = address(this).balance; Address.sendValue(payable(payoutAddress1), balance); }
function withdraw() public nonReentrant { uint256 balance = address(this).balance; Address.sendValue(payable(payoutAddress1), balance); }
15,954
232
// Cannot overflow, as that would require more tokens to be burned/transferred out than the owner initially received through minting and transferring in.
_balances[owner] -= 1;
_balances[owner] -= 1;
2,505
15
// The function initializes a group with a release date._id Group identifying number. _releaseTimestamp Unix timestamp of the time after which the tokens can be released /
function init(uint8 _id, uint _releaseTimestamp) internal { require(_releaseTimestamp > 0); Group storage group = groups[_id]; group.releaseTimestamp = _releaseTimestamp; }
function init(uint8 _id, uint _releaseTimestamp) internal { require(_releaseTimestamp > 0); Group storage group = groups[_id]; group.releaseTimestamp = _releaseTimestamp; }
36,351
124
// Changes the admin of `proxy` to `newAdmin`. Requirements: - This contract must be the current admin of `proxy`. /
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner { proxy.changeAdmin(newAdmin); }
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner { proxy.changeAdmin(newAdmin); }
4,458
25
// Triggered whenever approve(address _spender, uint256 _amount) is called
event Approval(address indexed _owner, address indexed _spender, uint256 _amount);
event Approval(address indexed _owner, address indexed _spender, uint256 _amount);
9,790
178
// Emit the `Transfer` event. Similar to above.
log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
5,231
342
// Validates transfer and reverts on rejection. May emit logs. cToken Asset being transferred src The account which sources the tokens dst The account which receives the tokens transferTokens The number of cTokens to transfer /
function transferVerify(address cToken, address src, address dst, uint transferTokens) external { cToken; // currently unused src; // currently unused dst; // currently unused transferTokens; // currently unused if (false) { maxAssets = maxAssets; // not pure } }
function transferVerify(address cToken, address src, address dst, uint transferTokens) external { cToken; // currently unused src; // currently unused dst; // currently unused transferTokens; // currently unused if (false) { maxAssets = maxAssets; // not pure } }
6,157
8
// Auth roles
address public minter; address public pauser; address public feeRecipient;
address public minter; address public pauser; address public feeRecipient;
51,040
22
// Set success to whether it returned true.
success := iszero(iszero(mload(0)))
success := iszero(iszero(mload(0)))
35,683
54
// require(path.length-exchanges.length==1 ,'wrong path and exchange nums');require(path[0]==path[path.length-1],'Ist no a cycle');
for (uint i = 0; i < path.length - 1; i++) { if (i == 0) { ThispairAddress = returnPairAddress( exchanges[i], path[i], path[i + 1] ); TransferHelper.safeTransferFrom( path[i], msg.sender,
for (uint i = 0; i < path.length - 1; i++) { if (i == 0) { ThispairAddress = returnPairAddress( exchanges[i], path[i], path[i + 1] ); TransferHelper.safeTransferFrom( path[i], msg.sender,
3,871
21
// ---------------------------------------------------------------------------- Contract function to receive approval and execute function in one call Borrowed from MiniMeToken ----------------------------------------------------------------------------
contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; }
contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; }
9,507
21
// all good
if (msg.sender != tokenOwner) { revert("caller not owner"); }
if (msg.sender != tokenOwner) { revert("caller not owner"); }
4,691
109
// return The version of the pool.
function version() external view returns (uint);
function version() external view returns (uint);
43,699
0
// to position this {TimelockController} as the owner of a smart contract, with/ Emitted when a call is scheduled as part of operation `id`. /
event CallScheduled( bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay );
event CallScheduled( bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay );
2,315
37
//
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); }
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); }
36
102
// tokenId => (ownerAddress => bidAddress)
mapping(uint256 => mapping(address =>address payable)) private auctionBidders;
mapping(uint256 => mapping(address =>address payable)) private auctionBidders;
17,269
28
// Returns the minimum and maximum number of validators that can be elected.return The minimum and maximum number of validators that can be elected. /
function getElectableValidators() external view returns (uint256, uint256) { return (electableValidators.min, electableValidators.max); }
function getElectableValidators() external view returns (uint256, uint256) { return (electableValidators.min, electableValidators.max); }
19,067
37
// This function makes it easy to get the total number of reputation/ return The total number of reputation
function totalSupply() public view returns (uint256) { return totalSupplyAt(block.number); }
function totalSupply() public view returns (uint256) { return totalSupplyAt(block.number); }
29,527
370
// Ensure that the provided URI is not empty /
modifier onlyValidURI(string memory uri) { require( bytes(uri).length != 0, "Media: specified uri must be non-empty" ); _; }
modifier onlyValidURI(string memory uri) { require( bytes(uri).length != 0, "Media: specified uri must be non-empty" ); _; }
4,949
12
// User that can grant access permissions and perform privileged actions
function owner() external view returns (address);
function owner() external view returns (address);
1,615
12
// Lets an authorized address lazy mint a given amount of NFTs. _amount The number of NFTs to lazy mint._baseURIForTokens The placeholder base URI for the 'n' number of NFTs being lazy minted, where the
* metadata for each of those NFTs is `${baseURIForTokens}/${tokenId}`. * @param _data The encrypted base URI + provenance hash for the batch of NFTs being lazy minted. * @return batchId A unique integer identifier for the batch of NFTs lazy minted together. */ function lazyMint( uint256 _amount, string calldata _baseURIForTokens, bytes calldata _data ) public virtual override returns (uint256 batchId) { if (_data.length > 0) { (bytes memory encryptedURI, bytes32 provenanceHash) = abi.decode(_data, (bytes, bytes32)); if (encryptedURI.length != 0 && provenanceHash != "") { _setEncryptedData(nextTokenIdToLazyMint + _amount, _data); } } return LazyMint.lazyMint(_amount, _baseURIForTokens, _data); }
* metadata for each of those NFTs is `${baseURIForTokens}/${tokenId}`. * @param _data The encrypted base URI + provenance hash for the batch of NFTs being lazy minted. * @return batchId A unique integer identifier for the batch of NFTs lazy minted together. */ function lazyMint( uint256 _amount, string calldata _baseURIForTokens, bytes calldata _data ) public virtual override returns (uint256 batchId) { if (_data.length > 0) { (bytes memory encryptedURI, bytes32 provenanceHash) = abi.decode(_data, (bytes, bytes32)); if (encryptedURI.length != 0 && provenanceHash != "") { _setEncryptedData(nextTokenIdToLazyMint + _amount, _data); } } return LazyMint.lazyMint(_amount, _baseURIForTokens, _data); }
178
157
// @note: this is going to a regular account. the existing balance has already been reduced, and as such the only thing to do is to send the actual Shyft fuel (or Ether, etc) to the target address.
_to.transfer(_value); emit EVT_WithdrawToAddress(msg.sender, _to, _value); ok = true;
_to.transfer(_value); emit EVT_WithdrawToAddress(msg.sender, _to, _value); ok = true;
1,677
157
// Only registered adapters are allowed to execute the function call. /
modifier onlyAdapter(DaoRegistry dao) { require( (dao.state() == DaoRegistry.DaoState.CREATION && creationModeCheck(dao)) || dao.isAdapter(msg.sender), "onlyAdapter" ); _; }
modifier onlyAdapter(DaoRegistry dao) { require( (dao.state() == DaoRegistry.DaoState.CREATION && creationModeCheck(dao)) || dao.isAdapter(msg.sender), "onlyAdapter" ); _; }
63,471
46
// increate the delegate's delegatee balance
balanceOfDelegatees[delegateToAccept_]++; emit DelegateSet(msg.sender, delegateToAccept_);
balanceOfDelegatees[delegateToAccept_]++; emit DelegateSet(msg.sender, delegateToAccept_);
29,014
5
// Sets template parameters for a pool type index. poolIdx The index of the pool type. feeRate The pool's swap fee rate in multiples of 0.0001% tickSize The pool's grid size in ticks. jitThresh The minimum resting time (in seconds) for concentrated LPs. knockout The knockout bits for the pool template.
function setTemplate (bytes calldata input) private { (, uint256 poolIdx, uint16 feeRate, uint16 tickSize, uint8 jitThresh, uint8 knockout, uint8 oracleFlags) = abi.decode(input, (uint8, uint256, uint16, uint16, uint8, uint8, uint8)); emit CrocEvents.SetPoolTemplate(poolIdx, feeRate, tickSize, jitThresh, knockout, oracleFlags); setPoolTemplate(poolIdx, feeRate, tickSize, jitThresh, knockout, oracleFlags); }
function setTemplate (bytes calldata input) private { (, uint256 poolIdx, uint16 feeRate, uint16 tickSize, uint8 jitThresh, uint8 knockout, uint8 oracleFlags) = abi.decode(input, (uint8, uint256, uint16, uint16, uint8, uint8, uint8)); emit CrocEvents.SetPoolTemplate(poolIdx, feeRate, tickSize, jitThresh, knockout, oracleFlags); setPoolTemplate(poolIdx, feeRate, tickSize, jitThresh, knockout, oracleFlags); }
32,403
52
// update token's price with new price
BitPixelnft.price = _newPrice;
BitPixelnft.price = _newPrice;
10,455
4
// Gold that has been unlocked and will become available for withdrawal.
PendingWithdrawal[] pendingWithdrawals;
PendingWithdrawal[] pendingWithdrawals;
21,286
22
// Percentage of house edge fees to be rewarded to losing gambler.
uint public rewardPct = 20;
uint public rewardPct = 20;
19,529
45
// is provider initiated/oracleAddress the provider address/ return Whether or not the provider has initiated in the Registry.
function isProviderInitiated(address oracleAddress) public view returns (bool) { return getProviderTitle(oracleAddress) != 0; }
function isProviderInitiated(address oracleAddress) public view returns (bool) { return getProviderTitle(oracleAddress) != 0; }
26,291
15
// Update maximum staked amount
function updateMaxStakeAmount(uint256 _newMaxStakeAmount) external onlyOwner { maxStakeAmount = _newMaxStakeAmount; }
function updateMaxStakeAmount(uint256 _newMaxStakeAmount) external onlyOwner { maxStakeAmount = _newMaxStakeAmount; }
17,979
263
// ACCESS LIMITED: For situation where all target units met and remaining WETH, uniformly raise targets by same percentage by applyingto logged positionMultiplier in RebalanceInfo struct, in order to allow further trading. Can be called multiple times if necessary,targets are increased by amount specified by raiseAssetTargetsPercentage as set by manager. In order to reduce tracking errorraising the target by a smaller amount allows greater granularity in finding an equilibrium between the excess ETH and componentsthat need to be bought. Raising the targets too much could result in vastly under allocating to WETH as more WETH than necessary isspent buying the components
function raiseAssetTargets(ISetToken _setToken) external onlyAllowedTrader(_setToken) virtual { require( _allTargetsMet(_setToken) && _getDefaultPositionRealUnit(_setToken, weth) > _getNormalizedTargetUnit(_setToken, weth), "Targets not met or ETH =~ 0" ); // positionMultiplier / (10^18 + raiseTargetPercentage) // ex: (10 ** 18) / ((10 ** 18) + ether(.0025)) => 997506234413965087 rebalanceInfo[_setToken].positionMultiplier = rebalanceInfo[_setToken].positionMultiplier.preciseDiv( PreciseUnitMath.preciseUnit().add(rebalanceInfo[_setToken].raiseTargetPercentage) ); emit AssetTargetsRaised(_setToken, rebalanceInfo[_setToken].positionMultiplier); }
function raiseAssetTargets(ISetToken _setToken) external onlyAllowedTrader(_setToken) virtual { require( _allTargetsMet(_setToken) && _getDefaultPositionRealUnit(_setToken, weth) > _getNormalizedTargetUnit(_setToken, weth), "Targets not met or ETH =~ 0" ); // positionMultiplier / (10^18 + raiseTargetPercentage) // ex: (10 ** 18) / ((10 ** 18) + ether(.0025)) => 997506234413965087 rebalanceInfo[_setToken].positionMultiplier = rebalanceInfo[_setToken].positionMultiplier.preciseDiv( PreciseUnitMath.preciseUnit().add(rebalanceInfo[_setToken].raiseTargetPercentage) ); emit AssetTargetsRaised(_setToken, rebalanceInfo[_setToken].positionMultiplier); }
33,903
21
// send `value` token to `to` from `from`from The address of the senderto The address of the recipientvalue The amount of token to be transferred return the transaction address and send the event as Transfer
function transferFrom(address from, address to, uint256 value) public { require ( allowed[from][msg.sender] >= value && balances[from] >= value && value > 0 ); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); Transfer(from, to, value); }
function transferFrom(address from, address to, uint256 value) public { require ( allowed[from][msg.sender] >= value && balances[from] >= value && value > 0 ); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); Transfer(from, to, value); }
8,622
27
// makes sure weiSend of current tx is reset
modifier weiSendGuard() { weiSend = msg.value; _; weiSend = 0; }
modifier weiSendGuard() { weiSend = msg.value; _; weiSend = 0; }
8,797
157
// If the latest observation occurred in the past, then no tick-changing trades have happened in this block therefore the tick in `slot0` is the same as at the beginning of the current block. We don't need to check if this observation is initialized - it is guaranteed to be.
(uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) = IUniswapV3Pool(pool).observations(observationIndex); if (observationTimestamp != uint32(block.timestamp)) { return (tick, IUniswapV3Pool(pool).liquidity()); }
(uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) = IUniswapV3Pool(pool).observations(observationIndex); if (observationTimestamp != uint32(block.timestamp)) { return (tick, IUniswapV3Pool(pool).liquidity()); }
45,590
24
// will add an address to PaymentSplitter by onlyDev roleaddress newAddy - address to recieve paymentsuint newShares - number of shares they recieve
function addPayee(address newAddy, uint newShares) public onlyDev { require(!lockedPayees, "Can not set, payees locked"); _addPayee(newAddy, newShares); }
function addPayee(address newAddy, uint newShares) public onlyDev { require(!lockedPayees, "Can not set, payees locked"); _addPayee(newAddy, newShares); }
16,681
264
// Because the exponent is larger than one, the base of the power function has a lower bound. We cap to this value to avoid numeric issues, which means in the extreme case (where the invariant growth is larger than 1 / min exponent) the Pool will pay less in protocol fees than it should.
base = Math.max(base, FixedPoint.MIN_POW_BASE_FREE_EXPONENT); uint256 power = base.powUp(exponent); uint256 tokenAccruedFees = balance.mulDown(power.complement()); return tokenAccruedFees.mulDown(protocolSwapFeePercentage);
base = Math.max(base, FixedPoint.MIN_POW_BASE_FREE_EXPONENT); uint256 power = base.powUp(exponent); uint256 tokenAccruedFees = balance.mulDown(power.complement()); return tokenAccruedFees.mulDown(protocolSwapFeePercentage);
14,948
211
// Returns the validator accumulated rewards on stake manager.
function validatorReward(uint256 validatorId) external view returns (uint256);
function validatorReward(uint256 validatorId) external view returns (uint256);
44,616
66
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
uniswapV2Router = _uniswapV2Router;
237
178
// The new version of the validator set
ValsetArgs memory _newValset,
ValsetArgs memory _newValset,
27,695
23
// Read and consume the next 16 bytes from the buffer as an `uint128`._buffer An instance of `BufferLib.Buffer`. return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position./
function readUint128(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint128 value; assembly { value := mload(add(add(bytesValue, 16), offset)) } _buffer.cursor += 16; return value; }
function readUint128(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint128 value; assembly { value := mload(add(add(bytesValue, 16), offset)) } _buffer.cursor += 16; return value; }
6,771
7
// A function that can only be called by the owner (i.e., only the owner can sell tokens back to the curve and withdraw the funds). The price is_n number of tokens to be sold back to the curve./
function burn(uint256 _n) internal { require(msg.sender == owner, "only the owner can sell tokens back to the curve and withdraw the funds"); uint256 _sellPrice = this.sellPrice(_n); _balances[msg.sender] = _balances[msg.sender].sub(_n); currentSupply_x = currentSupply_x.sub(_n); emit Transfer(owner, 0x0, _n); }
function burn(uint256 _n) internal { require(msg.sender == owner, "only the owner can sell tokens back to the curve and withdraw the funds"); uint256 _sellPrice = this.sellPrice(_n); _balances[msg.sender] = _balances[msg.sender].sub(_n); currentSupply_x = currentSupply_x.sub(_n); emit Transfer(owner, 0x0, _n); }
45,229
53
// ======== ADDRESS ======== // ======== BOOL ======== // ======== UINT ======== // ======== CONSTRUCTOR ======== /
constructor(uint _initialSupply, address _recipient) ERC20("Abacus", "ABC") { _mint(_recipient, _initialSupply); admin = msg.sender; }
constructor(uint _initialSupply, address _recipient) ERC20("Abacus", "ABC") { _mint(_recipient, _initialSupply); admin = msg.sender; }
34,159
27
// If the portal is set, the xChain message will be sent
honeyJarPortal.sendStartGame{value: msg.value}(
honeyJarPortal.sendStartGame{value: msg.value}(
23,461
53
// Mint of the same token with different amounts to different receivers
for (uint i = 0; i < to.length; i++) { _mint(to[i], tokenIds[0], amounts[i], new bytes(0)); }
for (uint i = 0; i < to.length; i++) { _mint(to[i], tokenIds[0], amounts[i], new bytes(0)); }
7,058
274
// Returns true if there are 2 elements that are the same in an arrayA The input array to search return Returns boolean for the first occurrence of a duplicate/
function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; }
function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; }
10,848
167
// Returns data about a specific observation index/index The element of the observations array to fetch/You most likely want to use observe() instead of this method to get an observation as of some amount of time/ ago, rather than at a specific index in the array./ return blockTimestamp The timestamp of the observation,/ Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,/ Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,/ Returns initialized whether the observation has been initialized and the
function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized );
function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized );
37,037
81
// Devuelve el historico de hashes asociado a un ID si el ID tiene algún hash almacenado en el SC, en otro caso devuelve un array vacio./ externalId El id externo por el que buscar el hash. Por ejemplo su identificador en la base de datos/ appId El nombre de la aplicacion que registró el hash: Xej:Biomasa/return hashes Información de los hashes y su número de bloque de ethereum asociado
function getHashesHistoryById(string calldata externalId, string calldata appId) external view returns (HashBlockNumer [] memory hashes) { bytes32 id = keccak256(abi.encode(appId, externalId)); HashBlockNumer memory current = id2hash[id]; if (current.blockNumber == 0) { return new HashBlockNumer [] (0); } HashBlockNumer [] storage history = bnHistoryById[id]; HashBlockNumer [] memory arrayHistorico = new HashBlockNumer [] (history.length + 1); for (uint256 i = 0; i<arrayHistorico.length-1; i++) { arrayHistorico[i] = history[i]; } arrayHistorico[arrayHistorico.length-1] = current; return arrayHistorico; }
function getHashesHistoryById(string calldata externalId, string calldata appId) external view returns (HashBlockNumer [] memory hashes) { bytes32 id = keccak256(abi.encode(appId, externalId)); HashBlockNumer memory current = id2hash[id]; if (current.blockNumber == 0) { return new HashBlockNumer [] (0); } HashBlockNumer [] storage history = bnHistoryById[id]; HashBlockNumer [] memory arrayHistorico = new HashBlockNumer [] (history.length + 1); for (uint256 i = 0; i<arrayHistorico.length-1; i++) { arrayHistorico[i] = history[i]; } arrayHistorico[arrayHistorico.length-1] = current; return arrayHistorico; }
56,889
95
// Allows a request to be cancelled if it has not been fulfilled Requires keeping track of the expiration value emitted from the oracle contract.Deletes the request from the `pendingRequests` mapping.Emits ChainlinkCancelled event. _requestId The request ID _payment The amount of LINK sent for the request _callbackFunc The callback function specified for the request _expiration The time of the expiration for the request /
function cancelChainlinkRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) internal
function cancelChainlinkRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) internal
46,026
107
// FIXME: 统一权限管理
modifier auth { require( msg.sender == admin || msg.sender == bankEntryAddress, "msg.sender need admin or bank" ); _; }
modifier auth { require( msg.sender == admin || msg.sender == bankEntryAddress, "msg.sender need admin or bank" ); _; }
26,780
1
// Returns the list of tickers owned by the selected address _owner is the address which owns the list of tickers /
function getTickersByOwner(address _owner) external view returns(bytes32[] memory) { uint256 count = 0; // accessing the data structure userTotickers[_owner].length bytes32[] memory tickers = getArrayBytes32(Encoder.getKey("userToTickers", _owner)); uint i; for (i = 0; i < tickers.length; i++) { if (_ownerInTicker(tickers[i])) { count++; } } bytes32[] memory result = new bytes32[](count); count = 0; for (i = 0; i < tickers.length; i++) { if (_ownerInTicker(tickers[i])) { result[count] = tickers[i]; count++; } } return result; }
function getTickersByOwner(address _owner) external view returns(bytes32[] memory) { uint256 count = 0; // accessing the data structure userTotickers[_owner].length bytes32[] memory tickers = getArrayBytes32(Encoder.getKey("userToTickers", _owner)); uint i; for (i = 0; i < tickers.length; i++) { if (_ownerInTicker(tickers[i])) { count++; } } bytes32[] memory result = new bytes32[](count); count = 0; for (i = 0; i < tickers.length; i++) { if (_ownerInTicker(tickers[i])) { result[count] = tickers[i]; count++; } } return result; }
38,680
18
// Add markets to idleMarkets, allowing them to earn IDLE in the flywheel idleTokens The addresses of the markets to add /
function _addIdleMarkets(address[] memory idleTokens) public { require(adminOrInitializing(), "only admin can change idle rate"); for (uint256 i = 0; i < idleTokens.length; i++) { _addIdleMarketInternal(idleTokens[i]); } refreshIdleSpeedsInternal(); }
function _addIdleMarkets(address[] memory idleTokens) public { require(adminOrInitializing(), "only admin can change idle rate"); for (uint256 i = 0; i < idleTokens.length; i++) { _addIdleMarketInternal(idleTokens[i]); } refreshIdleSpeedsInternal(); }
8,588
49
// 读取待审核公益组织
function getVerifyUsers() view returns (uint256[]){ uint256[] uIds; for (uint i = 1; i <= userIndex; i++) { User user=indexToUser[i]; if(!user.enable){ uIds.push(i); } } return uIds; }
function getVerifyUsers() view returns (uint256[]){ uint256[] uIds; for (uint i = 1; i <= userIndex; i++) { User user=indexToUser[i]; if(!user.enable){ uIds.push(i); } } return uIds; }
45,289
57
// Deal with relative offsets
if (_relative) { require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking"); _offset += _buffer.cursor; }
if (_relative) { require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking"); _offset += _buffer.cursor; }
1,948