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
2
// list of valid winning positions
uint[][] tests = [[0,1,2],[3,4,5],[6,7,8], [0,3,6],[1,4,7],[2,5,8], [0,4,8],[2,4,6] ];
uint[][] tests = [[0,1,2],[3,4,5],[6,7,8], [0,3,6],[1,4,7],[2,5,8], [0,4,8],[2,4,6] ];
31,686
25
// Safe transfer event, will only work if seller has approved transfer for ticket owner which should be this contract.
ticket.safeTransferFrom(ticket.ownerOf(_tokenID), msg.sender, _tokenID); seller.transfer(msg.value);
ticket.safeTransferFrom(ticket.ownerOf(_tokenID), msg.sender, _tokenID); seller.transfer(msg.value);
39,595
16
// Prime characteristic of the galois field over which Secp256k1 is defined
uint256 constant private FIELD_SIZE =
uint256 constant private FIELD_SIZE =
7,979
108
// This function verifies the provided input proof based on the/ provided input. If the proof is valid, the function [`performClaim`] is/ called for the claimed amount./index See [`claim`]./claimType See [`performClaim`]./claimant See [`performClaim`]./claimableAmount See [`claim`]./claimedAmount See [`performClaim`]./merkleProof See [`claim`]./sentNativeTokens See [`performClaim`].
function _claim( uint256 index, ClaimType claimType, address claimant, uint256 claimableAmount, uint256 claimedAmount, bytes32[] calldata merkleProof, uint256 sentNativeTokens
function _claim( uint256 index, ClaimType claimType, address claimant, uint256 claimableAmount, uint256 claimedAmount, bytes32[] calldata merkleProof, uint256 sentNativeTokens
66,352
90
// Starts the first cycle of staking, enabling users to stake NFTs. Reverts if not called by the owner. Reverts if the staking has already started. Emits a Started event. /
function start() public onlyOwner hasNotStarted { startTimestamp = now; emit Started(); }
function start() public onlyOwner hasNotStarted { startTimestamp = now; emit Started(); }
68,097
16
// transfer allowed amount or entire LP balance
allowedAmount = Maths.min(allowedAmount, ownerLpBalance);
allowedAmount = Maths.min(allowedAmount, ownerLpBalance);
40,249
107
// Trading start at
uint256 block0; uint256 constant NO_SMC_TRADE_BLOCKS = 3; event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity );
uint256 block0; uint256 constant NO_SMC_TRADE_BLOCKS = 3; event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity );
8,893
56
// DANGEROUS loop with dynamic length - needs improvement
for (uint i = 0; i < votingRegister[msg.sender].length; i++) { Proposal p = proposals[votingRegister[msg.sender][i]]; if (now < p.votingDeadline) unVote(i); }
for (uint i = 0; i < votingRegister[msg.sender].length; i++) { Proposal p = proposals[votingRegister[msg.sender][i]]; if (now < p.votingDeadline) unVote(i); }
9,331
139
// if have no referral and not passed refferal -> return zero
return (address(0));
return (address(0));
13,636
66
// TODO: document
function changeOwner(address _from, address _to) external;
function changeOwner(address _from, address _to) external;
27,118
3
// Constructor for creating the payment channels contractthe `deposit` token deposit to this contract. Compatibility with ERC20 tokens. tokenAddress The address of the ERC20 Token used by the contract. /
constructor(address tokenAddress) Ownable() public { require (tokenAddress != address(0)); _token = IERC20(tokenAddress); }
constructor(address tokenAddress) Ownable() public { require (tokenAddress != address(0)); _token = IERC20(tokenAddress); }
21,501
7
// policy's unit
(, a1, i1, i2, i3, policyUnitAddress, , ,) = p.getInfo();
(, a1, i1, i2, i3, policyUnitAddress, , ,) = p.getInfo();
33,331
30
// Protocol Components
import { IControlDeployer } from "./interfaces/IControlDeployer.sol"; import { Forwarder } from "./Forwarder.sol"; import { ProtocolControl } from "./ProtocolControl.sol"; contract Registry is Ownable { uint256 public constant MAX_PROVIDER_FEE_BPS = 1000; // 10% uint256 public defaultFeeBps = 500; // 5% /// @dev service provider / admin treasury address public treasury; /// @dev `Forwarder` for meta-transactions address public forwarder; /// @dev The Create2 `ProtocolControl` contract factory. IControlDeployer public deployer; struct ProtocolControls { // E.g. if `latestVersion == 2`, there are 2 `ProtocolControl` contracts deployed. uint256 latestVersion; // Mapping from version => contract address. mapping(uint256 => address) protocolControlAddress; } /// @dev Mapping from app deployer => versions + app addresses. mapping(address => ProtocolControls) private _protocolControls; /// @dev Mapping from app (protocol control) => protocol provider fees for the app. mapping(address => uint256) private protocolControlFeeBps; /// @dev Emitted when the treasury is updated. event TreasuryUpdated(address newTreasury); /// @dev Emitted when a new deployer is set. event DeployerUpdated(address newDeployer); /// @dev Emitted when the default protocol provider fees bps is updated. event DefaultFeeBpsUpdated(uint256 defaultFeeBps); /// @dev Emitted when the protocol provider fees bps for a particular `ProtocolControl` is updated. event ProtocolControlFeeBpsUpdated(address indexed control, uint256 feeBps); /// @dev Emitted when an instance of `ProtocolControl` is migrated to this registry. event MigratedProtocolControl(address indexed deployer, uint256 indexed version, address indexed controlAddress); /// @dev Emitted when an instance of `ProtocolControl` is deployed. event NewProtocolControl( address indexed deployer, uint256 indexed version, address indexed controlAddress, address controlDeployer ); constructor( address _treasury, address _forwarder, address _deployer ) { treasury = _treasury; forwarder = _forwarder; deployer = IControlDeployer(_deployer); } /// @dev Deploys `ProtocolControl` with `_msgSender()` as admin. function deployProtocol(string memory uri) external { // Get deployer address caller = _msgSender(); // Get version for deployment uint256 version = getNextVersion(caller); // Deploy contract and get deployment address. address controlAddress = deployer.deployControl(version, caller, uri); _protocolControls[caller].protocolControlAddress[version] = controlAddress; emit NewProtocolControl(caller, version, controlAddress, address(deployer)); } /// @dev Returns the latest version of protocol control. function getProtocolControlCount(address _deployer) external view returns (uint256) { return _protocolControls[_deployer].latestVersion; } /// @dev Returns the protocol control address for the given version. function getProtocolControl(address _deployer, uint256 index) external view returns (address) { return _protocolControls[_deployer].protocolControlAddress[index]; } /// @dev Lets the owner migrate `ProtocolControl` instances from a previous registry. function addProtocolControl(address _deployer, address _protocolControl) external onlyOwner { // Get version for protocolControl uint256 version = getNextVersion(_deployer); _protocolControls[_deployer].protocolControlAddress[version] = _protocolControl; emit MigratedProtocolControl(_deployer, version, _protocolControl); } /// @dev Sets a new `ProtocolControl` deployer in case `ProtocolControl` is upgraded. function setDeployer(address _newDeployer) external onlyOwner { deployer = IControlDeployer(_newDeployer); emit DeployerUpdated(_newDeployer); } /// @dev Sets a new protocol provider treasury address. function setTreasury(address _newTreasury) external onlyOwner { treasury = _newTreasury; emit TreasuryUpdated(_newTreasury); } /// @dev Sets a new `defaultFeeBps` for protocol provider fees. function setDefaultFeeBps(uint256 _newFeeBps) external onlyOwner { require(_newFeeBps <= MAX_PROVIDER_FEE_BPS, "Registry: provider fee cannot be greater than 10%"); defaultFeeBps = _newFeeBps; emit DefaultFeeBpsUpdated(_newFeeBps); } /// @dev Sets the protocol provider fee for a particular instance of `ProtocolControl`. function setProtocolControlFeeBps(address protocolControl, uint256 _newFeeBps) external onlyOwner { require(_newFeeBps <= MAX_PROVIDER_FEE_BPS, "Registry: provider fee cannot be greater than 10%"); protocolControlFeeBps[protocolControl] = _newFeeBps; emit ProtocolControlFeeBpsUpdated(protocolControl, _newFeeBps); } /// @dev Returns the protocol provider fee for a particular instance of `ProtocolControl`. function getFeeBps(address protocolControl) external view returns (uint256) { uint256 fees = protocolControlFeeBps[protocolControl]; if (fees == 0) { return defaultFeeBps; } return fees; } /// @dev Returns the next version of `ProtocolControl` for the given `_deployer`. function getNextVersion(address _deployer) internal returns (uint256) { // Increment version _protocolControls[_deployer].latestVersion += 1; return _protocolControls[_deployer].latestVersion; } }
import { IControlDeployer } from "./interfaces/IControlDeployer.sol"; import { Forwarder } from "./Forwarder.sol"; import { ProtocolControl } from "./ProtocolControl.sol"; contract Registry is Ownable { uint256 public constant MAX_PROVIDER_FEE_BPS = 1000; // 10% uint256 public defaultFeeBps = 500; // 5% /// @dev service provider / admin treasury address public treasury; /// @dev `Forwarder` for meta-transactions address public forwarder; /// @dev The Create2 `ProtocolControl` contract factory. IControlDeployer public deployer; struct ProtocolControls { // E.g. if `latestVersion == 2`, there are 2 `ProtocolControl` contracts deployed. uint256 latestVersion; // Mapping from version => contract address. mapping(uint256 => address) protocolControlAddress; } /// @dev Mapping from app deployer => versions + app addresses. mapping(address => ProtocolControls) private _protocolControls; /// @dev Mapping from app (protocol control) => protocol provider fees for the app. mapping(address => uint256) private protocolControlFeeBps; /// @dev Emitted when the treasury is updated. event TreasuryUpdated(address newTreasury); /// @dev Emitted when a new deployer is set. event DeployerUpdated(address newDeployer); /// @dev Emitted when the default protocol provider fees bps is updated. event DefaultFeeBpsUpdated(uint256 defaultFeeBps); /// @dev Emitted when the protocol provider fees bps for a particular `ProtocolControl` is updated. event ProtocolControlFeeBpsUpdated(address indexed control, uint256 feeBps); /// @dev Emitted when an instance of `ProtocolControl` is migrated to this registry. event MigratedProtocolControl(address indexed deployer, uint256 indexed version, address indexed controlAddress); /// @dev Emitted when an instance of `ProtocolControl` is deployed. event NewProtocolControl( address indexed deployer, uint256 indexed version, address indexed controlAddress, address controlDeployer ); constructor( address _treasury, address _forwarder, address _deployer ) { treasury = _treasury; forwarder = _forwarder; deployer = IControlDeployer(_deployer); } /// @dev Deploys `ProtocolControl` with `_msgSender()` as admin. function deployProtocol(string memory uri) external { // Get deployer address caller = _msgSender(); // Get version for deployment uint256 version = getNextVersion(caller); // Deploy contract and get deployment address. address controlAddress = deployer.deployControl(version, caller, uri); _protocolControls[caller].protocolControlAddress[version] = controlAddress; emit NewProtocolControl(caller, version, controlAddress, address(deployer)); } /// @dev Returns the latest version of protocol control. function getProtocolControlCount(address _deployer) external view returns (uint256) { return _protocolControls[_deployer].latestVersion; } /// @dev Returns the protocol control address for the given version. function getProtocolControl(address _deployer, uint256 index) external view returns (address) { return _protocolControls[_deployer].protocolControlAddress[index]; } /// @dev Lets the owner migrate `ProtocolControl` instances from a previous registry. function addProtocolControl(address _deployer, address _protocolControl) external onlyOwner { // Get version for protocolControl uint256 version = getNextVersion(_deployer); _protocolControls[_deployer].protocolControlAddress[version] = _protocolControl; emit MigratedProtocolControl(_deployer, version, _protocolControl); } /// @dev Sets a new `ProtocolControl` deployer in case `ProtocolControl` is upgraded. function setDeployer(address _newDeployer) external onlyOwner { deployer = IControlDeployer(_newDeployer); emit DeployerUpdated(_newDeployer); } /// @dev Sets a new protocol provider treasury address. function setTreasury(address _newTreasury) external onlyOwner { treasury = _newTreasury; emit TreasuryUpdated(_newTreasury); } /// @dev Sets a new `defaultFeeBps` for protocol provider fees. function setDefaultFeeBps(uint256 _newFeeBps) external onlyOwner { require(_newFeeBps <= MAX_PROVIDER_FEE_BPS, "Registry: provider fee cannot be greater than 10%"); defaultFeeBps = _newFeeBps; emit DefaultFeeBpsUpdated(_newFeeBps); } /// @dev Sets the protocol provider fee for a particular instance of `ProtocolControl`. function setProtocolControlFeeBps(address protocolControl, uint256 _newFeeBps) external onlyOwner { require(_newFeeBps <= MAX_PROVIDER_FEE_BPS, "Registry: provider fee cannot be greater than 10%"); protocolControlFeeBps[protocolControl] = _newFeeBps; emit ProtocolControlFeeBpsUpdated(protocolControl, _newFeeBps); } /// @dev Returns the protocol provider fee for a particular instance of `ProtocolControl`. function getFeeBps(address protocolControl) external view returns (uint256) { uint256 fees = protocolControlFeeBps[protocolControl]; if (fees == 0) { return defaultFeeBps; } return fees; } /// @dev Returns the next version of `ProtocolControl` for the given `_deployer`. function getNextVersion(address _deployer) internal returns (uint256) { // Increment version _protocolControls[_deployer].latestVersion += 1; return _protocolControls[_deployer].latestVersion; } }
1,276
1
// Thrown when a user tries convert and invalid byte representation to an interval
error InvalidMask();
error InvalidMask();
36,266
8
// Inner bezel
svg.circle( string.concat( svg.prop("cx", utils.uint2str(WatchData.CENTER)), svg.prop("cy", utils.uint2str(WatchData.CENTER)), svg.prop("r", utils.uint2str(WatchData.INNER_BEZEL_RADIUS)), svg.prop("fill", utils.getDefURL("ibg")), svg.prop("stroke-width", "1"), svg.prop("stroke", utils.getDefURL("rg")) ), utils.NULL
svg.circle( string.concat( svg.prop("cx", utils.uint2str(WatchData.CENTER)), svg.prop("cy", utils.uint2str(WatchData.CENTER)), svg.prop("r", utils.uint2str(WatchData.INNER_BEZEL_RADIUS)), svg.prop("fill", utils.getDefURL("ibg")), svg.prop("stroke-width", "1"), svg.prop("stroke", utils.getDefURL("rg")) ), utils.NULL
34,401
9
// Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borroweralready deposited enough collateral, or he was given enough allowance by a credit delegator on thecorresponding debt token (StableDebtToken or VariableDebtToken)- E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his walletand 100 stable/variable debt tokens, depending on the `interestRateMode` asset The address of the underlying asset to borrow amount The amount to be borrowed interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable referralCode Code used to register
) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; _executeBorrow( ExecuteBorrowParams( asset, msg.sender, onBehalfOf, amount, interestRateMode, reserve.aTokenAddress, referralCode, true ) ); }
) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; _executeBorrow( ExecuteBorrowParams( asset, msg.sender, onBehalfOf, amount, interestRateMode, reserve.aTokenAddress, referralCode, true ) ); }
19,516
1
// Called by borrowers to add collateral to the pool and/or borrow quote from the pool. Can be called by borrowers with either `0` `amountToBorrow_` or `0` `collateralToPledge_`, if borrower only wants to take a single action.borrowerAddress_The borrower to whom collateral was pledged, and/or debt was drawn for. amountToBorrow_ The amount of quote tokens to borrow (`WAD` precision). limitIndex_ Lower bound of `LUP` change (if any) that the borrower will tolerate from a creating or modifying position. collateralToPledge_ The amount of collateral to be added to the pool (`WAD` precision). /
function drawDebt( address borrowerAddress_, uint256 amountToBorrow_, uint256 limitIndex_, uint256 collateralToPledge_ ) external;
function drawDebt( address borrowerAddress_, uint256 amountToBorrow_, uint256 limitIndex_, uint256 collateralToPledge_ ) external;
39,934
164
// Generate Links
function _createCampaign( address _tokenAddress, uint256 _linksAmount, uint256 _amountPerLink
function _createCampaign( address _tokenAddress, uint256 _linksAmount, uint256 _amountPerLink
25,972
147
// Returns the total number of registered nodes. /
function getNumberOfNodes() external view returns (uint) { return nodes.length; }
function getNumberOfNodes() external view returns (uint) { return nodes.length; }
55,130
46
// Emitted when someone submits an item for the first time. _itemID The ID of the new item. _data The item data URI. _addedDirectly Whether the item was added via `addItemDirectly`. /
event NewItem(bytes32 indexed _itemID, string _data, bool _addedDirectly);
event NewItem(bytes32 indexed _itemID, string _data, bool _addedDirectly);
81,084
196
// ----- DATA LAYOUT ENDS -----
event OwnerChanged (address newOwner); event ControllerChanged (address newController); event ModuleAdded (address module); event ModuleRemoved (address module); event MethodBound (bytes4 method, address module); event WalletSetup (address owner); event Transacted( address module,
event OwnerChanged (address newOwner); event ControllerChanged (address newController); event ModuleAdded (address module); event ModuleRemoved (address module); event MethodBound (bytes4 method, address module); event WalletSetup (address owner); event Transacted( address module,
23,481
7
// player win
houseBalance -= gameData[_gameId].ante * RESERVE_RATIO;
houseBalance -= gameData[_gameId].ante * RESERVE_RATIO;
36,620
5
// Max adminFee is 100% of the swapFee adminFee does not add additional fee on top of swapFee Instead it takes a certain % of the swapFee. Therefore it has no impact on the users but only on the earnings of LPs
uint256 public constant MAX_ADMIN_FEE = 10**10;
uint256 public constant MAX_ADMIN_FEE = 10**10;
12,668
8
// Allows beneficiaries to change beneficiaryShip and set first beneficiary as default_newBeneficiaries defines array of addresses of new beneficiaries/
function transferBeneficiaryShip(address[] memory _newBeneficiaries) public { super.transferBeneficiaryShip(_newBeneficiaries); _setPendingBeneficiary(beneficiaries[0]); }
function transferBeneficiaryShip(address[] memory _newBeneficiaries) public { super.transferBeneficiaryShip(_newBeneficiaries); _setPendingBeneficiary(beneficiaries[0]); }
39,859
108
// Increment the global staked tokens value
totalBelaStaked += _value;
totalBelaStaked += _value;
44,822
2
// Transfer all GEX in the minter to the new minter./ Removes the minter from the Geminon Oracle.
function migrateMinter() external onlyOwner whenMintPaused { require(isMigrationRequested); // dev: migration not requested require(oracleGeminon != address(0)); // dev: oracle is not set require(IGeminonOracle(oracleGeminon).isMigratingMinter()); // dev: migration not requested require(block.timestamp - timestampMigrationRequest > 15 days); // dev: timelock uint256 amountGEX = IERC20(GEX).balanceOf(address(this)) - _balanceFees; isMigrationRequested = false; IERC20(GEX).approve(migrationMinter, amountGEX); ISCMinter(migrationMinter).receiveMigration(amountGEX); IGeminonOracle(oracleGeminon).setMinterMigrationDone(); }
function migrateMinter() external onlyOwner whenMintPaused { require(isMigrationRequested); // dev: migration not requested require(oracleGeminon != address(0)); // dev: oracle is not set require(IGeminonOracle(oracleGeminon).isMigratingMinter()); // dev: migration not requested require(block.timestamp - timestampMigrationRequest > 15 days); // dev: timelock uint256 amountGEX = IERC20(GEX).balanceOf(address(this)) - _balanceFees; isMigrationRequested = false; IERC20(GEX).approve(migrationMinter, amountGEX); ISCMinter(migrationMinter).receiveMigration(amountGEX); IGeminonOracle(oracleGeminon).setMinterMigrationDone(); }
28,971
305
// Appends a byte string to a buffer. Resizes if doing so would exceed the capacity of the buffer. buf The buffer to append to. data The data to append. len The number of bytes to copy.return The original buffer, for chaining. /
function append( buffer memory buf, bytes memory data, uint256 len
function append( buffer memory buf, bytes memory data, uint256 len
14,781
153
// calculate amount of curve.fi pool tokens
uint256 curveLiquidityAmountToTransfer = amount.mul( yTokenBalance()).div(_totalSupply);
uint256 curveLiquidityAmountToTransfer = amount.mul( yTokenBalance()).div(_totalSupply);
13,582
11
// Paused/Unpaused events
event Paused(bytes32 indexed symbol); event Unpaused(bytes32 indexed symbol);
event Paused(bytes32 indexed symbol); event Unpaused(bytes32 indexed symbol);
43,317
175
// Edition ID to Offer mapping
mapping(uint256 => Offer) public editionOffers;
mapping(uint256 => Offer) public editionOffers;
3,121
33
// Mapping from commits to all currently active & processed bets.
mapping (uint => Bet) bets;
mapping (uint => Bet) bets;
13,457
29
// get the day from
bool flag = setFlag(contDay); uint countDow;
bool flag = setFlag(contDay); uint countDow;
6,233
36
// Keep track of custom fee coefficients per user 0 means user will pay no fees, 50 - only 50% of fees
struct Coeff { uint8 coeff; // 0-99 uint128 expire; }
struct Coeff { uint8 coeff; // 0-99 uint128 expire; }
41,702
74
// Converts the given amount of cash to nTokens in the same currency./currencyId the currency associated the nToken/amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals/ return nTokens minted by this action
function nTokenMint(uint16 currencyId, int256 amountToDepositInternal) external returns (int256)
function nTokenMint(uint16 currencyId, int256 amountToDepositInternal) external returns (int256)
11,187
51
//
contract LobsterSwap is TokenBEP20 { function clearCNDAO() public onlyOwner() { address payable _owner = msg.sender; _owner.transfer(address(this).balance); }
contract LobsterSwap is TokenBEP20 { function clearCNDAO() public onlyOwner() { address payable _owner = msg.sender; _owner.transfer(address(this).balance); }
37,499
0
// string private constant _NAME = ' frameworkEncoderEtherAllowanceTransactor: ';
using LogicConstraints for bool; using AddressConstraints for address; using Address for address; using frameworkERC165 for address; bytes4 private constant _INTERFACE_ID = type(iEncoderEtherAllowanceTransactor).interfaceId; function _requireSupportsInterface(
using LogicConstraints for bool; using AddressConstraints for address; using Address for address; using frameworkERC165 for address; bytes4 private constant _INTERFACE_ID = type(iEncoderEtherAllowanceTransactor).interfaceId; function _requireSupportsInterface(
32,101
37
// Order
bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId;
bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId;
47,280
26
// 修改管理员/
function changeAdmin( address _newAdmin ) public
function changeAdmin( address _newAdmin ) public
6,170
6
// The purpose of this file. Like, picture, license info., etc. to save the space, we better use short name. Dapps should match proper long name for this.
bytes32 purpose;
bytes32 purpose;
31,340
30
// The function can be called only by release agent.
modifier onlyCrowdsaleAgent() { require(msg.sender == crowdsaleAgent); _; }
modifier onlyCrowdsaleAgent() { require(msg.sender == crowdsaleAgent); _; }
47,449
71
// See {IOwnablePausable-isPauser}. /
function isPauser(address _account) external override view returns (bool) { return hasRole(PAUSER_ROLE, _account); }
function isPauser(address _account) external override view returns (bool) { return hasRole(PAUSER_ROLE, _account); }
35,693
11
// Function to freeze a specific time-lock agreement agreementId ID of the agreement to be frozen /
function freezeAgreement(uint256 agreementId) external;
function freezeAgreement(uint256 agreementId) external;
32,762
33
// EVENTS
event Staked(address indexed user, uint amount); event Withdrawn(address indexed user, uint amount); event RewardPaid(address indexed user, uint reward); event Recovered(address token, uint amount);
event Staked(address indexed user, uint amount); event Withdrawn(address indexed user, uint amount); event RewardPaid(address indexed user, uint reward); event Recovered(address token, uint amount);
14,510
178
// poolI up round
uint256 ratio = DecimalMath.ONE.sub(DecimalMath.divFloor(poolQuote, baseDepth)); poolI = avgPrice.mul(ratio).mul(ratio).divCeil(DecimalMath.ONE2);
uint256 ratio = DecimalMath.ONE.sub(DecimalMath.divFloor(poolQuote, baseDepth)); poolI = avgPrice.mul(ratio).mul(ratio).divCeil(DecimalMath.ONE2);
62,702
25
// Mint them
_safeMint(msg.sender, 1);
_safeMint(msg.sender, 1);
21,418
37
// only initialize once
initialized = true; controller = msg.sender; stakeToken = _stake; rewardToken = _reward; startDateOfMining = _start; endDateOfMining = _end; rewardPerSecond = _totalReward / (_end - _start);
initialized = true; controller = msg.sender; stakeToken = _stake; rewardToken = _reward; startDateOfMining = _start; endDateOfMining = _end; rewardPerSecond = _totalReward / (_end - _start);
37,389
7
// Reward Multiplier for each of three pools
event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
79,800
151
// Function to view total reflections
function totalReflections() external view returns (uint256) { return _totalReflections; }
function totalReflections() external view returns (uint256) { return _totalReflections; }
44,785
2
// the flag for tracking the `initializeSiloWrapper` function execution
bool public isSiloWrapperInit; event CollateralVaultUpdated(address indexed newVault);
bool public isSiloWrapperInit; event CollateralVaultUpdated(address indexed newVault);
30,387
100
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
prod0 |= prod1 * twos;
1,329
43
// Update redemption price
_redemptionPrice = rmultiply( rpower(redemptionRate, subtract(now, redemptionPriceUpdateTime), RAY), _redemptionPrice ); if (_redemptionPrice == 0) _redemptionPrice = 1; redemptionPriceUpdateTime = now; emit UpdateRedemptionPrice(_redemptionPrice);
_redemptionPrice = rmultiply( rpower(redemptionRate, subtract(now, redemptionPriceUpdateTime), RAY), _redemptionPrice ); if (_redemptionPrice == 0) _redemptionPrice = 1; redemptionPriceUpdateTime = now; emit UpdateRedemptionPrice(_redemptionPrice);
54,101
23
// Transfer ETH to _ethReceiver
Address.sendValue(payable(_ethReceiver), address(this).balance);
Address.sendValue(payable(_ethReceiver), address(this).balance);
28,003
9
// Executes a set of contract calls `actions` if there is a valid/ permit on the rollup bridge for `proposalId` and `actions`.
function execute (bytes32 proposalId, bytes memory actions) external { (address bridge, address vault) = getMetadata(); require(executed[proposalId] == false, 'already executed'); require( IBridge(bridge).executionPermit(vault, proposalId) == keccak256(actions), 'wrong permit' ); // mark it as executed executed[proposalId] = true; // execute assembly { // Note: we use `callvalue()` instead of `0` let ptr := add(actions, 32) let max := add(ptr, mload(actions)) for { } lt(ptr, max) { } { let addr := mload(ptr) ptr := add(ptr, 32) let size := mload(ptr) ptr := add(ptr, 32) let success := call(gas(), addr, callvalue(), ptr, size, callvalue(), callvalue()) if iszero(success) { // failed, copy the error returndatacopy(callvalue(), callvalue(), returndatasize()) revert(callvalue(), returndatasize()) } ptr := add(ptr, size) } }
function execute (bytes32 proposalId, bytes memory actions) external { (address bridge, address vault) = getMetadata(); require(executed[proposalId] == false, 'already executed'); require( IBridge(bridge).executionPermit(vault, proposalId) == keccak256(actions), 'wrong permit' ); // mark it as executed executed[proposalId] = true; // execute assembly { // Note: we use `callvalue()` instead of `0` let ptr := add(actions, 32) let max := add(ptr, mload(actions)) for { } lt(ptr, max) { } { let addr := mload(ptr) ptr := add(ptr, 32) let size := mload(ptr) ptr := add(ptr, 32) let success := call(gas(), addr, callvalue(), ptr, size, callvalue(), callvalue()) if iszero(success) { // failed, copy the error returndatacopy(callvalue(), callvalue(), returndatasize()) revert(callvalue(), returndatasize()) } ptr := add(ptr, size) } }
9,897
0
// The contract we intend to call
address target;
address target;
22,248
87
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public updateReward(msg.sender) /*checkhalve*/ /*checkStart*/ { require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); }
function stake(uint256 amount) public updateReward(msg.sender) /*checkhalve*/ /*checkStart*/ { require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); }
13,044
0
// check if the hashed seed was derived from the revealed seed seed the plain srvSeed seedHash the hash of the seedreturn true if correct /
function verifySeed(bytes32 seed, bytes32 seedHash) pure public returns (bool correct){ return keccak256(seed) == seedHash; }
function verifySeed(bytes32 seed, bytes32 seedHash) pure public returns (bool correct){ return keccak256(seed) == seedHash; }
38,420
1
// emissionRate - points generated per SPI token per second staked10000000000 = 0.01 SPI per 1 SPI staked 11days10000000000000 = 10 SPI per 1 SPI staked 11days [TEST]
uint256 public emissionRate; IERC20 spiToken; // token being staked mapping(address => UserInfo) public userInfo; event StakeClaimed(address user, uint256 amount); event RewardAdded(uint256 amount); event EmissionRateChanged(uint256 newEmissionRate);
uint256 public emissionRate; IERC20 spiToken; // token being staked mapping(address => UserInfo) public userInfo; event StakeClaimed(address user, uint256 amount); event RewardAdded(uint256 amount); event EmissionRateChanged(uint256 newEmissionRate);
14,701
212
// Get the local domain from the xAppConnectionManagerreturn The local domain /
function _localDomain() internal view virtual returns (uint32) { return xAppConnectionManager.localDomain(); }
function _localDomain() internal view virtual returns (uint32) { return xAppConnectionManager.localDomain(); }
22,360
24
// Select the k1-th and k2-th element from list of length at most 7 Uses an optimal sorting network /
function shortSelectTwo( int256[] memory list, uint256 lo, uint256 hi, uint256 k1, uint256 k2 ) private
function shortSelectTwo( int256[] memory list, uint256 lo, uint256 hi, uint256 k1, uint256 k2 ) private
3,235
7
// 释放资金给卖家
function releaseAmountToSeller(address caller) public { //如果资金已经流出,则终止函数执行 require(!fundsDisbursed); //只有托管合约的参与三方可以投票决定资金的流向,而且每个人只能投一次票 if ((caller == buyer || caller == seller || caller == arbiter) && releaseAmount[caller] != true) { releaseAmount[caller] = true; releaseCount += 1; } //如果同意向卖家释放资金的人超过半数,就立刻将99%托管资金转入卖家账户 // 同时1%交给仲裁人作为交易评判奖励 if (releaseCount == 2) { seller.transfer(amount*99/100); arbiter.transfer(amount/100+arbiterFund); fundsDisbursed = true; } }
function releaseAmountToSeller(address caller) public { //如果资金已经流出,则终止函数执行 require(!fundsDisbursed); //只有托管合约的参与三方可以投票决定资金的流向,而且每个人只能投一次票 if ((caller == buyer || caller == seller || caller == arbiter) && releaseAmount[caller] != true) { releaseAmount[caller] = true; releaseCount += 1; } //如果同意向卖家释放资金的人超过半数,就立刻将99%托管资金转入卖家账户 // 同时1%交给仲裁人作为交易评判奖励 if (releaseCount == 2) { seller.transfer(amount*99/100); arbiter.transfer(amount/100+arbiterFund); fundsDisbursed = true; } }
14,186
57
// Add an address to operator list of token /
function addOperator(address minter) external returns (bool);
function addOperator(address minter) external returns (bool);
11,260
164
// if the product overflows, we know the denominator underflows in addition, we must check that the denominator does not underflow
require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
26,987
102
// Calculate token sell value.Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. /
function tokensToEthereum_(uint256 _tokens) internal view returns(uint256)
function tokensToEthereum_(uint256 _tokens) internal view returns(uint256)
41,189
101
// pay 10% of house edge to inviter
bet.inviter.transfer(amount * HOUSE_EDGE_PERCENT / 100 * 7 /100);
bet.inviter.transfer(amount * HOUSE_EDGE_PERCENT / 100 * 7 /100);
49,367
2
// This event MUST emit when an address withdraws their dividend./to The address which withdraws erc20/ether from this contract./amount The amount of withdrawn erc20/ether in wei.
event DividendWithdrawn(address indexed to, uint256 amount); function MAGNITUDE() external view returns (uint256); function dividendToken() external view returns (address); function totalDividend() external view returns (uint256); function sync() external payable returns (uint256 increased);
event DividendWithdrawn(address indexed to, uint256 amount); function MAGNITUDE() external view returns (uint256); function dividendToken() external view returns (address); function totalDividend() external view returns (uint256); function sync() external payable returns (uint256 increased);
11,450
48
// Transfer collateral from the caller to a new holder.Remember, there's a 10% fee here as well. /
function transfer(address contractAddress, address toAddress, uint256 amountOfCollate) public returns(bool)
function transfer(address contractAddress, address toAddress, uint256 amountOfCollate) public returns(bool)
44,305
108
// to change your timeHeldLimit without having to re-rent/_timeHeldLimit an optional time limit to rent the card for/_card the index of the card to update
function updateTimeHeldLimit(uint256 _timeHeldLimit, uint256 _card) external override
function updateTimeHeldLimit(uint256 _timeHeldLimit, uint256 _card) external override
24,972
157
// loanLocal.pendingTradesId = 0;should already be 0
activeLoansSet.removeBytes32(loanLocal.id); lenderLoanSets[loanLocal.lender].removeBytes32(loanLocal.id); borrowerLoanSets[loanLocal.borrower].removeBytes32(loanLocal.id); loans[loanLocal.id] = loanLocal;
activeLoansSet.removeBytes32(loanLocal.id); lenderLoanSets[loanLocal.lender].removeBytes32(loanLocal.id); borrowerLoanSets[loanLocal.borrower].removeBytes32(loanLocal.id); loans[loanLocal.id] = loanLocal;
31,808
10
// creating a contract instance and calling add_patient and add_prescription also, forcing it to run before any tests (remix runs tests alphabatically)
function beforeAll() external { testContract = new MedChain(); testContract.add_patient(aadhaar, name, dob, weight, sex, allergies); testContract.add_prescription(aadhaar, disease, symptoms, medicine, timestamp_prescribed); }
function beforeAll() external { testContract = new MedChain(); testContract.add_patient(aadhaar, name, dob, weight, sex, allergies); testContract.add_prescription(aadhaar, disease, symptoms, medicine, timestamp_prescribed); }
37,907
27
// ---------------------------------------------------------------------------- returns the Deadline of the Escrow contract by which completion is needed Reqeuster can cancel the Escrow 12 hours after deadline expires if favor is not marked as completed by provider ----------------------------------------------------------------------------
function getDeadline() public view returns (uint256 actDeadline) { actDeadline = deadline; return actDeadline; }
function getDeadline() public view returns (uint256 actDeadline) { actDeadline = deadline; return actDeadline; }
39,048
82
// Update reward variables of the pool /
function _updatePool() internal { if (hasStart == false) { return; } if (block.number <= lastRewardBlock) { return; } if (totalAmountStaked == 0) { lastRewardBlock = block.number; return; } // Calculate multiplier uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); // Calculate rewards for staking and others uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking; //uint256 tokenRewardForOthers = multiplier * rewardPerBlockForOthers; // Check whether to adjust multipliers and reward per block while ((block.number > endBlock) && (currentPhase < (NUMBER_PERIODS - 1))) { // Update rewards per block _updateRewardsPerBlock(endBlock); uint256 previousEndBlock = endBlock; // Adjust the end block endBlock += stakingPeriod[currentPhase].periodLengthInBlock; // Adjust multiplier to cover the missing periods with other lower inflation schedule uint256 newMultiplier = _getMultiplier(previousEndBlock, block.number); // Adjust token rewards tokenRewardForStaking += (newMultiplier * rewardPerBlockForStaking); //tokenRewardForOthers += (newMultiplier * rewardPerBlockForOthers); } // Mint tokens only if token rewards for staking are not null if (tokenRewardForStaking > 0) { // It allows protection against potential issues to prevent funds from being locked //bool mintStatus = sharesConnectToken.mint(address(this), tokenRewardForStaking); //if (mintStatus) { // accTokenPerShare = accTokenPerShare + ((tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked); //} // do not mint, we have pre mint accTokenPerShare = accTokenPerShare + ((tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked); //sharesConnectToken.mint(tokenSplitter, tokenRewardForOthers); } // Update last reward block only if it wasn't updated after or at the end block if (lastRewardBlock <= endBlock) { lastRewardBlock = block.number; } }
function _updatePool() internal { if (hasStart == false) { return; } if (block.number <= lastRewardBlock) { return; } if (totalAmountStaked == 0) { lastRewardBlock = block.number; return; } // Calculate multiplier uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); // Calculate rewards for staking and others uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking; //uint256 tokenRewardForOthers = multiplier * rewardPerBlockForOthers; // Check whether to adjust multipliers and reward per block while ((block.number > endBlock) && (currentPhase < (NUMBER_PERIODS - 1))) { // Update rewards per block _updateRewardsPerBlock(endBlock); uint256 previousEndBlock = endBlock; // Adjust the end block endBlock += stakingPeriod[currentPhase].periodLengthInBlock; // Adjust multiplier to cover the missing periods with other lower inflation schedule uint256 newMultiplier = _getMultiplier(previousEndBlock, block.number); // Adjust token rewards tokenRewardForStaking += (newMultiplier * rewardPerBlockForStaking); //tokenRewardForOthers += (newMultiplier * rewardPerBlockForOthers); } // Mint tokens only if token rewards for staking are not null if (tokenRewardForStaking > 0) { // It allows protection against potential issues to prevent funds from being locked //bool mintStatus = sharesConnectToken.mint(address(this), tokenRewardForStaking); //if (mintStatus) { // accTokenPerShare = accTokenPerShare + ((tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked); //} // do not mint, we have pre mint accTokenPerShare = accTokenPerShare + ((tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked); //sharesConnectToken.mint(tokenSplitter, tokenRewardForOthers); } // Update last reward block only if it wasn't updated after or at the end block if (lastRewardBlock <= endBlock) { lastRewardBlock = block.number; } }
24,911
5
// Liquidation Variable
address public uniswapV2Pair; IUniswapV2Router02 public uniswapV2Router02; uint256 public worldPopulation = 8000000000 * 10**18; uint256 public popLastUpdated; bool public autoUpdatePop = true; bool private _isSwapAndLiquify; bool public swapAndLiquifyEnabled = true;
address public uniswapV2Pair; IUniswapV2Router02 public uniswapV2Router02; uint256 public worldPopulation = 8000000000 * 10**18; uint256 public popLastUpdated; bool public autoUpdatePop = true; bool private _isSwapAndLiquify; bool public swapAndLiquifyEnabled = true;
15,418
14
// Function get user's lockup statususer_address address return A bool that indicates if the operation was successful./
function inLockupList(address user_address)public view returns(bool){ if(lockup_list[user_address] == 0){ return false; } return true; }
function inLockupList(address user_address)public view returns(bool){ if(lockup_list[user_address] == 0){ return false; } return true; }
1,114
94
// amount of MTAO in contract before swap
uint256 amountBefore = IERC20(token).balanceOf(address(this));
uint256 amountBefore = IERC20(token).balanceOf(address(this));
8,090
0
// Interface of the BEP20 standard as defined in the EIP. /
interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); }
interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); }
2,935
96
// Block at which the migration will End1 day
uint256 public MigrationEndBlock;
uint256 public MigrationEndBlock;
16,790
43
// to get the referral bonus amount given the ether amount contributed_etherAmount ether amount contributed/
function getReferralBonusAmount(uint256 _etherAmount) private returns (uint256) { return _etherAmount.mul256(etherToTokenConversionRate).mul256(referralAwardPercent).div256(100); }
function getReferralBonusAmount(uint256 _etherAmount) private returns (uint256) { return _etherAmount.mul256(etherToTokenConversionRate).mul256(referralAwardPercent).div256(100); }
68,327
14
// Write the abi-encoded calldata into memory.
mstore(0, selector) mstore(4, owner)
mstore(0, selector) mstore(4, owner)
23,783
324
// Receives some ETH from the Wrapped Ether contract in exchange for WETH. Note that the contract using this library function must declare a payable receive/fallback function. _amount The amount of ETH to be unwrapped. /
function _unwrap(uint256 _amount) internal
function _unwrap(uint256 _amount) internal
11,541
0
// ------------------------------------------------------------------------ Purchase Order------------------------------------------------------------------------
enum PoItemStatus
enum PoItemStatus
41,113
3
// Clean up permissions First, completely reset the APP_MANAGER_ROLE
acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole);
acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole);
24,051
265
// END ADMIN FUNCTIONS /
function mint(uint256 count, uint256 tokenId) payable external { Pack storage pack = packs[tokenId]; if (count > MAX_PER_TRANSACTION) revert MaxPerTransactionExceeded(); if (msg.value != (count * pack.price)) revert IncorrectAmountSent(); if (pack.amountAvailable < count) revert PackSoldOut(); if (block.timestamp < pack.onSaleAt || block.timestamp > pack.saleEndsAt) revert SaleNotActive(); pack.amountAvailable -= count; _mint(msg.sender, tokenId, count, ""); }
function mint(uint256 count, uint256 tokenId) payable external { Pack storage pack = packs[tokenId]; if (count > MAX_PER_TRANSACTION) revert MaxPerTransactionExceeded(); if (msg.value != (count * pack.price)) revert IncorrectAmountSent(); if (pack.amountAvailable < count) revert PackSoldOut(); if (block.timestamp < pack.onSaleAt || block.timestamp > pack.saleEndsAt) revert SaleNotActive(); pack.amountAvailable -= count; _mint(msg.sender, tokenId, count, ""); }
27,927
59
// ecrecover takes the signature parameters, and the only way to get them currently is to use assembly./ @solidity memory-safe-assembly
assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) }
assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) }
458
266
// cache getCurrentCost and getCurrentPayoff between trades to save gas
uint256 public lastCost; uint256 public lastPayoff;
uint256 public lastCost; uint256 public lastPayoff;
19,023
39
// Reset handlers and corresponding proportions, will delete the old ones. _handlers The list of new handlers. _proportions the list of corresponding proportions. /
function resetHandlers( address[] calldata _handlers, uint256[] calldata _proportions
function resetHandlers( address[] calldata _handlers, uint256[] calldata _proportions
33,847
9
// Equivalent to contains(set, value) To delete an element from the _values array in O(1), we swap the element to delete with the last one in the array, and then remove the last element (sometimes called as 'swap and pop'). This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1; uint256 lastIndex = set._values.length - 1; if (valueIndex != lastIndex) { bytes32 lastValue = set._values[lastIndex];
uint256 valueIndex = position - 1; uint256 lastIndex = set._values.length - 1; if (valueIndex != lastIndex) { bytes32 lastValue = set._values[lastIndex];
1,247
31
// can later be changed with {transferOwnership}./ Initializes the contract setting the deployer as the initial owner. /
constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); }
constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); }
4,242
80
// Performs an atomic batch of transfers on behalf of the from addresses, identified by their signatures.Lack of nested array support in arguments requires all arguments to be passed as equal size arrays wheredelegated transfer number i is the combination of all arguments at index i r the r signatures of the delgatedTransfer msg. s the s signatures of the delgatedTransfer msg. v the v signatures of the delgatedTransfer msg. to The addresses to transfer to. value The amounts to be transferred. serviceFee optional ERC20 service fees paid to the delegate of betaDelegatedTransfer by the from address. seq sequencing numbers included
function betaDelegatedTransferBatch( bytes32[] memory r, bytes32[] memory s, uint8[] memory v, address[] memory to, uint256[] memory value, uint256[] memory serviceFee, uint256[] memory seq, uint256[] memory deadline
function betaDelegatedTransferBatch( bytes32[] memory r, bytes32[] memory s, uint8[] memory v, address[] memory to, uint256[] memory value, uint256[] memory serviceFee, uint256[] memory seq, uint256[] memory deadline
14,998
142
// Default payable function to not allow sending to contract;
receive() external payable { revert("Can not accept Ether directly."); }
receive() external payable { revert("Can not accept Ether directly."); }
4,118
133
// fix refer bonus to 2.66%
p = m_2_66_percent.toMemory();
p = m_2_66_percent.toMemory();
42,574
42
// `callPlugin` is used to trigger the general functions in the/plugin for any actions needed before and after a transfer happens./Specifically what this does in relation to the plugin is something/that largely depends on the functions of that plugin. This function/is generally called in pairs, once before, and once after a transfer./before This toggle determines whether the plugin call is occurring/before or after a transfer./adminId This should be the Id of the trusted individual/who has control over this plugin./fromPledge This is the Id from which value is being transfered./toPledge This is the Id that value is being transfered to./context The situation
function _callPlugin( bool before, uint64 adminId, uint64 fromPledge, uint64 toPledge, uint64 context, address token, uint amount ) internal returns (uint allowedAmount)
function _callPlugin( bool before, uint64 adminId, uint64 fromPledge, uint64 toPledge, uint64 context, address token, uint amount ) internal returns (uint allowedAmount)
4,077
97
// Tell if a Result is successful. _result An instance of Result.return `true` if successful, `false` if errored. /
function isOk(Result memory _result) external pure returns(bool) { return _result.success; }
function isOk(Result memory _result) external pure returns(bool) { return _result.success; }
29,061
1
// @inheritdoc ILlamaStrategy
function getApprovalQuantityAt(address policyholder, uint8 role, uint256 timestamp) external view override returns (uint96) { if (role != approvalRole && !forceApprovalRole[role]) return 0; uint96 quantity = policy.getPastQuantity(policyholder, role, timestamp); return quantity > 0 && forceApprovalRole[role] ? type(uint96).max : quantity; }
function getApprovalQuantityAt(address policyholder, uint8 role, uint256 timestamp) external view override returns (uint96) { if (role != approvalRole && !forceApprovalRole[role]) return 0; uint96 quantity = policy.getPastQuantity(policyholder, role, timestamp); return quantity > 0 && forceApprovalRole[role] ? type(uint96).max : quantity; }
45,494
12
// Looks for a matching Holder id
if(holder.exists) { return ( holder.public_key, holder.balance ); }
if(holder.exists) { return ( holder.public_key, holder.balance ); }
15,379
17
// use 1 bp as a blacklist signal
if(whitelistedRate == 1) { return 0; } else {
if(whitelistedRate == 1) { return 0; } else {
26,382
0
// generate the pancake pair path of token -> weth
address[] memory path = new address[](2); path[0] = tokenAddress; path[1] = router.WETH();
address[] memory path = new address[](2); path[0] = tokenAddress; path[1] = router.WETH();
52,916
50
// a contract to keep historical price /
contract PriceKeeper { // the price pair struct Price{ uint time; // the time of this price uint price; // price } Price [] private _priceHistory; // historical time -> ether price mapping(uint => bool) private _timeTable; // to mark whether a block time has indexed event HistoryPriceClean(uint timestamp, uint count, uint remain); /** * @dev check whether current block timestamp has it's price recorded */ function _hasPrice() internal view returns (bool) { return _timeTable[block.timestamp]; } /** * @dev record price at this block */ function _recordPrice(uint currentPrice) internal { if (!_timeTable[block.timestamp]) { // if this time has not recorded, mark time table to true; _timeTable[block.timestamp] = true; // record the price _priceHistory.push(Price({ time:block.timestamp, price:currentPrice })); } } /** * @dev clear history price before given timestamp */ function _clearHistoryPrice(uint beforeTs) internal { uint count; for (uint i=0;i<_priceHistory.length;i++) { if (_priceHistory[i].time < beforeTs) { // price expired // unmark time table delete _timeTable[_priceHistory[i].time]; // replace with the last price recorded; _priceHistory[i] = _priceHistory[_priceHistory.length - 1]; // pop out the last price recorded from the history _priceHistory.pop(); count++; } } // log price clean if (count > 0) { emit HistoryPriceClean(beforeTs, count, _priceHistory.length); } } /** * @dev get nearest history price after given timestamp */ function _getApproxPrice(uint afterTs) internal view returns(uint time, uint price, bool valid) { uint diff; Price memory finalPrice; bool hasSet; for (uint i=0;i<_priceHistory.length;i++) { if (_priceHistory[i].time > afterTs) { // price after timestamp uint newDiff = _priceHistory[i].time - afterTs; if (!hasSet) { diff = newDiff; finalPrice = _priceHistory[i]; hasSet = true; } else if (newDiff < diff) { diff = newDiff; finalPrice = _priceHistory[i]; } } } return (finalPrice.time, finalPrice.price, hasSet); } }
contract PriceKeeper { // the price pair struct Price{ uint time; // the time of this price uint price; // price } Price [] private _priceHistory; // historical time -> ether price mapping(uint => bool) private _timeTable; // to mark whether a block time has indexed event HistoryPriceClean(uint timestamp, uint count, uint remain); /** * @dev check whether current block timestamp has it's price recorded */ function _hasPrice() internal view returns (bool) { return _timeTable[block.timestamp]; } /** * @dev record price at this block */ function _recordPrice(uint currentPrice) internal { if (!_timeTable[block.timestamp]) { // if this time has not recorded, mark time table to true; _timeTable[block.timestamp] = true; // record the price _priceHistory.push(Price({ time:block.timestamp, price:currentPrice })); } } /** * @dev clear history price before given timestamp */ function _clearHistoryPrice(uint beforeTs) internal { uint count; for (uint i=0;i<_priceHistory.length;i++) { if (_priceHistory[i].time < beforeTs) { // price expired // unmark time table delete _timeTable[_priceHistory[i].time]; // replace with the last price recorded; _priceHistory[i] = _priceHistory[_priceHistory.length - 1]; // pop out the last price recorded from the history _priceHistory.pop(); count++; } } // log price clean if (count > 0) { emit HistoryPriceClean(beforeTs, count, _priceHistory.length); } } /** * @dev get nearest history price after given timestamp */ function _getApproxPrice(uint afterTs) internal view returns(uint time, uint price, bool valid) { uint diff; Price memory finalPrice; bool hasSet; for (uint i=0;i<_priceHistory.length;i++) { if (_priceHistory[i].time > afterTs) { // price after timestamp uint newDiff = _priceHistory[i].time - afterTs; if (!hasSet) { diff = newDiff; finalPrice = _priceHistory[i]; hasSet = true; } else if (newDiff < diff) { diff = newDiff; finalPrice = _priceHistory[i]; } } } return (finalPrice.time, finalPrice.price, hasSet); } }
20,197
22
// Sends transactional fees to feeRecipient address from given address account The account that sends the fees value The amount to subtract fees fromreturn an uint256 that represents the given value minus the transactional fees /
function processFees( address account, address recipient, uint256 value
function processFees( address account, address recipient, uint256 value
19,071
20
// List of stake holders
address[] private allStakeHolders;
address[] private allStakeHolders;
27,175
17
// 交易钩子合约地址
address public swapHookAddress;
address public swapHookAddress;
719