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
24
// Fields:
string public constant name = "Grand Marche Token"; string public constant symbol = "GMT"; uint public constant decimals = 18; uint public constant TOTAL_SUPPLY = 1000000 * (1 ether / 1 wei); uint public constant AIRDROP_SHARE = 50000 * (1 ether / 1 wei); uint public constant PRESALE_PRICE = 250; // per 1 Ether uint public constant PRESALE_MAX_ETH = 400;
string public constant name = "Grand Marche Token"; string public constant symbol = "GMT"; uint public constant decimals = 18; uint public constant TOTAL_SUPPLY = 1000000 * (1 ether / 1 wei); uint public constant AIRDROP_SHARE = 50000 * (1 ether / 1 wei); uint public constant PRESALE_PRICE = 250; // per 1 Ether uint public constant PRESALE_MAX_ETH = 400;
32,965
106
// Check made maximum babies
require(getData().doneMaxBabies(male, female), "You need to make maximum amount of babies before you leave");
require(getData().doneMaxBabies(male, female), "You need to make maximum amount of babies before you leave");
43,819
2
// get the article
function getArticle() public view returns ( address _seller, string memory _name, string memory _description,
function getArticle() public view returns ( address _seller, string memory _name, string memory _description,
12,389
10
// Mints tokenIds into 'to' account Emits SftTokenTransfer Event Throws if sender has no MINTER_ROLE'data' holds the CFolioItemHandler if CFI's are minted /
function mintBatch( address to, uint256[] calldata tokenIds, bytes calldata data ) external;
function mintBatch( address to, uint256[] calldata tokenIds, bytes calldata data ) external;
30,814
31
// gas savings
if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numeratorTeam = totalSupply.mul(rootK.sub(rootKLast)).mul(2); uint denominatorTeam = rootK.mul(3).add(rootKLast.mul(2)); uint liquidityTeam = numeratorTeam / denominatorTeam; if (liquidityTeam > 0) { _mint(teamFeeTo, liquidityTeam);
if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numeratorTeam = totalSupply.mul(rootK.sub(rootKLast)).mul(2); uint denominatorTeam = rootK.mul(3).add(rootKLast.mul(2)); uint liquidityTeam = numeratorTeam / denominatorTeam; if (liquidityTeam > 0) { _mint(teamFeeTo, liquidityTeam);
56,829
109
// Standard ERC223 function that will handle incoming token transfers._fromToken sender address. _value Amount of tokens. _dataTransaction metadata. /
function tokenFallback(address _from, uint _value, bytes memory _data) public;
function tokenFallback(address _from, uint _value, bytes memory _data) public;
7,360
116
// This abstract contract provides getters and event emitting update functions for _Available since v4.1._ /
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { AddressUpgradeable.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { AddressUpgradeable.functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { AddressUpgradeable.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { AddressUpgradeable.functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
9,347
5
// Check if an extension can mint /
function _checkMintPermissions(address[] memory to, uint256[] memory tokenIds, uint256[] memory amounts) internal { if (_extensionPermissions[msg.sender] != address(0)) { IERC1155CreatorMintPermissions(_extensionPermissions[msg.sender]).approveMint(msg.sender, to, tokenIds, amounts); } }
function _checkMintPermissions(address[] memory to, uint256[] memory tokenIds, uint256[] memory amounts) internal { if (_extensionPermissions[msg.sender] != address(0)) { IERC1155CreatorMintPermissions(_extensionPermissions[msg.sender]).approveMint(msg.sender, to, tokenIds, amounts); } }
14,027
63
// fallback function - do not accept payment/
function () external payable { revert(); }
function () external payable { revert(); }
40,535
83
// 1 week as a timestamp.
uint256 private oneWeek = 604800;
uint256 private oneWeek = 604800;
77,708
114
// Max supply.
uint256 public constant SUPPLY_MAX = 10000;
uint256 public constant SUPPLY_MAX = 10000;
24,688
72
// IUniMexPool(pool).repay(owed);
IUniMexPool(pool).distribute(fees.div(2)); IUniMexStaking(staking).distribute(fees.sub(fees.div(2))); transferEscrowToUser(position.owner, position.owner, commitment.add(profitMinusFees)); position.isClosed = true;
IUniMexPool(pool).distribute(fees.div(2)); IUniMexStaking(staking).distribute(fees.sub(fees.div(2))); transferEscrowToUser(position.owner, position.owner, commitment.add(profitMinusFees)); position.isClosed = true;
19,468
36
// Address must not already be a solver and must not be a null address
require(!isSolver[_solvers[i]] && _solvers[i] != address(0)); isSolver[_solvers[i]] = true;
require(!isSolver[_solvers[i]] && _solvers[i] != address(0)); isSolver[_solvers[i]] = true;
57,262
106
// /Calculates the auction price parameters, targetting 1% slippage every 10 minutes. Fair valueplaced in middle of price range. _currentSetDollarAmountThe 18 decimal value of one currenSet_nextSetDollarAmount The 18 decimal value of one nextSet_timeIncrement Amount of time to explore 1% of fair value price change_auctionLibraryPriceDivisorThe auction library price divisor_auctionTimeToPivotThe auction time to pivotreturn uint256The auctionStartPrice for rebalance auctionreturn uint256The auctionPivotPrice for rebalance auction /
function calculateAuctionPriceParameters( uint256 _currentSetDollarAmount, uint256 _nextSetDollarAmount, uint256 _timeIncrement, uint256 _auctionLibraryPriceDivisor, uint256 _auctionTimeToPivot ) internal view returns (uint256, uint256)
function calculateAuctionPriceParameters( uint256 _currentSetDollarAmount, uint256 _nextSetDollarAmount, uint256 _timeIncrement, uint256 _auctionLibraryPriceDivisor, uint256 _auctionTimeToPivot ) internal view returns (uint256, uint256)
8,707
22
// sets config AccessControllerInterface contract only owner can call this accessController new AccessControllerInterface contract address /
function setConfigAC(address accessController) external onlyOwner { _setConfigAC(accessController); }
function setConfigAC(address accessController) external onlyOwner { _setConfigAC(accessController); }
42,883
285
// Used to collect accumulated protocol fees. /
function collectProtocol( uint256 amount0, uint256 amount1, address to
function collectProtocol( uint256 amount0, uint256 amount1, address to
53,926
7
// Send to multiple addresses using two arrays whichincludes the address and the amount. addresses Array of addresses to send to amounts Array of amounts to send feeAmount Amount of fee to collect /
function multiTransfer( uint256 feeAmount, address[] memory addresses, uint256[] memory amounts
function multiTransfer( uint256 feeAmount, address[] memory addresses, uint256[] memory amounts
10,790
3
// Callback function /
function fulfillStockPrice(bytes32 _requestId, bytes32 _result) public recordChainlinkFulfillment(_requestId) { readData(_result); }
function fulfillStockPrice(bytes32 _requestId, bytes32 _result) public recordChainlinkFulfillment(_requestId) { readData(_result); }
3,324
72
// This will assign ownership, and also emit the Transfer event as per ERC721 draft
_transfer(0, _owner, newDogId); return newDogId;
_transfer(0, _owner, newDogId); return newDogId;
15,084
58
// unstaking possible after 0 days
uint256 public cliffTime = 0 days; uint256 public farmEnableat; uint256 public totalClaimedRewards = 0; uint256 private stakingAndDaoTokens = 100000e18; bool public farmEnabled = false; EnumerableSet.AddressSet private holders;
uint256 public cliffTime = 0 days; uint256 public farmEnableat; uint256 public totalClaimedRewards = 0; uint256 private stakingAndDaoTokens = 100000e18; bool public farmEnabled = false; EnumerableSet.AddressSet private holders;
40,970
168
// import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { Math } from "@openzeppelin/contracts/math/Math.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { AddressArrayUtils } from "contracts/lib/AddressArrayUtils.sol"; import { BaseAdapter } from "contracts/lib/BaseAdapter.sol"; import { ICErc20 } from "contracts/interfaces/ICErc20.sol"; import { IICManagerV2 } from "contracts/interfaces/IICManagerV2.sol"; import { IComptroller } from "contracts/interfaces/IComptroller.sol"; import { ICompoundLeverageModule } from "contracts/interfaces/ICompoundLeverageModule.sol"; import { ICompoundPriceOracle } from "contracts/interfaces/ICompoundPriceOracle.sol"; import { ISetToken } from "contracts/interfaces/ISetToken.sol"; import { PreciseUnitMath } from "contracts/lib/PreciseUnitMath.sol";
using Address for address; using AddressArrayUtils for address[]; using PreciseUnitMath for uint256; using SafeMath for uint256;
using Address for address; using AddressArrayUtils for address[]; using PreciseUnitMath for uint256; using SafeMath for uint256;
15,879
120
// See: {AccessController.hasRole} /
modifier onlyRole(bytes32 role) { require(MarketClientLib.hasRole(role), "Caller doesn't have role"); _; }
modifier onlyRole(bytes32 role) { require(MarketClientLib.hasRole(role), "Caller doesn't have role"); _; }
15,612
2
// send `_value` token to `_to` from `msg.sender`/_to The address of the recipient/_value The amount of token to be transferred/ return success Whether the transfer was successful or not
function transfer(address _to, uint256 _value) external returns (bool success);
function transfer(address _to, uint256 _value) external returns (bool success);
3,451
99
// Create an iterator. Reverts if item is not a list.self The RLP item. return An 'Iterator' over the item./
function iterator(RLPItem memory self) internal pure returns (Iterator memory) { require(isList(self)); uint ptr = self.memPtr + _payloadOffset(self.memPtr); return Iterator(self, ptr); }
function iterator(RLPItem memory self) internal pure returns (Iterator memory) { require(isList(self)); uint ptr = self.memPtr + _payloadOffset(self.memPtr); return Iterator(self, ptr); }
24,764
85
// Restricted access function which updates base URI used to construct ERC721Metadata.tokenURIRequires executor to have ROLE_URI_MANAGER permission_baseURI new base URI to set /
function setBaseURI(string memory _baseURI) public virtual { // verify the access permission require(isSenderInRole(ROLE_URI_MANAGER), "access denied"); // emit an event first - to log both old and new values emit BaseURIUpdated(msg.sender, baseURI, _baseURI); // and update base URI baseURI = _baseURI; }
function setBaseURI(string memory _baseURI) public virtual { // verify the access permission require(isSenderInRole(ROLE_URI_MANAGER), "access denied"); // emit an event first - to log both old and new values emit BaseURIUpdated(msg.sender, baseURI, _baseURI); // and update base URI baseURI = _baseURI; }
24,737
11
// Validation: ensure that the required stack depth is not above theMAX_STACK_DEPTH_REQUIREMENT /
function validateRequiredStackDepth(uint requiredStackDepth) returns (bool) { return requiredStackDepth <= _MAX_STACK_DEPTH_REQUIREMENT; }
function validateRequiredStackDepth(uint requiredStackDepth) returns (bool) { return requiredStackDepth <= _MAX_STACK_DEPTH_REQUIREMENT; }
19,000
18
// uint256 updatedTimestamp = now;
bytes32 flightKey = getFlightKey(airline, flightName, departureTime); require(!flightInList(flightsList, flightKey), 'Flight already exists!'); flights[flightKey].flightName = flightName; flights[flightKey].isRegistered = true; flights[flightKey].statusCode = STATUS_CODE_UNKNOWN; flights[flightKey].departureTime = departureTime; flights[flightKey].airline = airline; flightsList.push(flightKey);
bytes32 flightKey = getFlightKey(airline, flightName, departureTime); require(!flightInList(flightsList, flightKey), 'Flight already exists!'); flights[flightKey].flightName = flightName; flights[flightKey].isRegistered = true; flights[flightKey].statusCode = STATUS_CODE_UNKNOWN; flights[flightKey].departureTime = departureTime; flights[flightKey].airline = airline; flightsList.push(flightKey);
47,700
151
// NOVA tokens created per block.
uint256 public novaPerBlock;
uint256 public novaPerBlock;
11,336
31
// Decode an RLPItem into a boolean. This will not work if the / RLPItem is a list. /self The RLPItem. / return The decoded string.
function toBool(RLPItem memory self) internal constant returns (bool data) { if(!isData(self)) revert(); var (rStartPos, len) = _decode(self); if (len != 1) revert(); uint temp; assembly { temp := byte(0, mload(rStartPos)) } if (temp > 1) revert(); return temp == 1 ? true : false; }
function toBool(RLPItem memory self) internal constant returns (bool data) { if(!isData(self)) revert(); var (rStartPos, len) = _decode(self); if (len != 1) revert(); uint temp; assembly { temp := byte(0, mload(rStartPos)) } if (temp > 1) revert(); return temp == 1 ? true : false; }
53,490
6
// withdraw
actionsWithdraw[0] = Dydx.ActionArgs( { actionType: 1, accountId: 0, amount: Dydx.AssetAmount( { sign: false, denomination: 0, ref: 0, value: amount.value
actionsWithdraw[0] = Dydx.ActionArgs( { actionType: 1, accountId: 0, amount: Dydx.AssetAmount( { sign: false, denomination: 0, ref: 0, value: amount.value
17,241
36
// Transfers ownership of the contract to a new account (`newOwner`).Can only be called by the current owner. /
function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); }
function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); }
1,795
15
// Function to pick a winner in a specific raffle
function pickWinner() public raffleOwnerExists { Raffle storage currentRaffle = raffles[msg.sender]; require(!currentRaffle.lotteryStatus, "Lottery is still running"); require(currentRaffle.playerSelector.length > 0, "No players in the lottery"); require(currentRaffle.nftContract != address(0), "NFT contract not set"); uint256 index = random(msg.sender) % currentRaffle.playerSelector.length; address winner = currentRaffle.playerSelector[index]; emit Winner(winner, msg.sender); ERC721Base(currentRaffle.nftContract).transferFrom(msg.sender, winner, currentRaffle.tokenId); resetEntryCounts(msg.sender); delete currentRaffle.playerSelector; delete currentRaffle.players; currentRaffle.lotteryStatus = false; currentRaffle.nftContract = address(0); currentRaffle.tokenId = 0; currentRaffle.totalEntries = 0; }
function pickWinner() public raffleOwnerExists { Raffle storage currentRaffle = raffles[msg.sender]; require(!currentRaffle.lotteryStatus, "Lottery is still running"); require(currentRaffle.playerSelector.length > 0, "No players in the lottery"); require(currentRaffle.nftContract != address(0), "NFT contract not set"); uint256 index = random(msg.sender) % currentRaffle.playerSelector.length; address winner = currentRaffle.playerSelector[index]; emit Winner(winner, msg.sender); ERC721Base(currentRaffle.nftContract).transferFrom(msg.sender, winner, currentRaffle.tokenId); resetEntryCounts(msg.sender); delete currentRaffle.playerSelector; delete currentRaffle.players; currentRaffle.lotteryStatus = false; currentRaffle.nftContract = address(0); currentRaffle.tokenId = 0; currentRaffle.totalEntries = 0; }
35
33
// if we have it in the PublicSale add it
if (PSaleGroup > 0){ whiteListedStatus = PSaleGroup; }else{
if (PSaleGroup > 0){ whiteListedStatus = PSaleGroup; }else{
11,914
9
// transfer : Transfer token to another etherum address /
function transfer(address to, uint tokens) virtual override public returns (bool success) { require(to != address(0), "Null address"); require(tokens > 0, "Invalid Value"); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; }
function transfer(address to, uint tokens) virtual override public returns (bool success) { require(to != address(0), "Null address"); require(tokens > 0, "Invalid Value"); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; }
18,690
118
// split the contract balance into thirds
uint256 liqPart = contractTokenBalance.mul(_marketingDivisor).div(_liquidityFee); uint256 halfOfLiquify = liqPart.div(2); uint256 otherHalfOfLiquify = liqPart.div(2); uint256 marketingPart = contractTokenBalance.sub(halfOfLiquify).sub(otherHalfOfLiquify);
uint256 liqPart = contractTokenBalance.mul(_marketingDivisor).div(_liquidityFee); uint256 halfOfLiquify = liqPart.div(2); uint256 otherHalfOfLiquify = liqPart.div(2); uint256 marketingPart = contractTokenBalance.sub(halfOfLiquify).sub(otherHalfOfLiquify);
41,183
24
// investing contract address change
// function setInvContract(address _addr) onlyManager public { // inv_contract = _addr; // }
// function setInvContract(address _addr) onlyManager public { // inv_contract = _addr; // }
45,037
625
// Enables or disables the oracle in `data`, returning the updated value. /
function setOracleEnabled(bytes32 data, bool _oracleEnabled) internal pure returns (bytes32) { return data.insertBool(_oracleEnabled, _ORACLE_ENABLED_OFFSET); }
function setOracleEnabled(bytes32 data, bool _oracleEnabled) internal pure returns (bytes32) { return data.insertBool(_oracleEnabled, _ORACLE_ENABLED_OFFSET); }
24,300
23
// F3GDatasets library /
library F3GDatasets { struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 R3Amount; // amount distributed to nt uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // affiliate id used uint256 aff1sum; uint256 aff2sum; uint256 aff3sum; uint256 aff4sum; uint256 aff5sum; } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase uint256 prevres; // 上一轮或者奖池互换流入本轮的奖金 } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 dev; // % of buy in thats paid to dev } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 dev; // % of pot thats paid to dev } }
library F3GDatasets { struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 R3Amount; // amount distributed to nt uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // affiliate id used uint256 aff1sum; uint256 aff2sum; uint256 aff3sum; uint256 aff4sum; uint256 aff5sum; } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase uint256 prevres; // 上一轮或者奖池互换流入本轮的奖金 } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 dev; // % of buy in thats paid to dev } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 dev; // % of pot thats paid to dev } }
50,618
51
// Returns the number of decimals used to get its user representation.For example, if `decimals` equals `2`, a balance of `505` tokens shouldbe displayed to a user as `5,05` (`505 / 102`). Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; }
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; }
42,006
44
// Collect outstanding management fee/The outstanding management fee is calculated from the time the last fee is collected.
function takeOutstandingManagementFee() public returns (uint256){ SmartPoolStorage.Fee storage fee = SmartPoolStorage.load().fees[SmartPoolStorage.FeeType.MANAGEMENT_FEE]; uint256 outstandingFee = calcManagementFee(); if (outstandingFee == 0 || outstandingFee < fee.minLine) return 0; _mint(getRewards(), outstandingFee); fee.lastTimestamp = block.timestamp; emit TakeFee(SmartPoolStorage.FeeType.MANAGEMENT_FEE, address(0), outstandingFee); return outstandingFee; }
function takeOutstandingManagementFee() public returns (uint256){ SmartPoolStorage.Fee storage fee = SmartPoolStorage.load().fees[SmartPoolStorage.FeeType.MANAGEMENT_FEE]; uint256 outstandingFee = calcManagementFee(); if (outstandingFee == 0 || outstandingFee < fee.minLine) return 0; _mint(getRewards(), outstandingFee); fee.lastTimestamp = block.timestamp; emit TakeFee(SmartPoolStorage.FeeType.MANAGEMENT_FEE, address(0), outstandingFee); return outstandingFee; }
43,385
32
// mapping from EIN to resolver to allowance
mapping (uint => mapping (address => uint)) public resolverAllowances;
mapping (uint => mapping (address => uint)) public resolverAllowances;
13,533
14
// if(accumulateStake[msg.sender] > 0){
if(firstMinStakeValue > 0 && poolInfo[_pid].accumulateStake[msg.sender] == 0){ require(amount >= firstMinStakeValue, "FROG-POOL: Cannot stake 0"); } else{
if(firstMinStakeValue > 0 && poolInfo[_pid].accumulateStake[msg.sender] == 0){ require(amount >= firstMinStakeValue, "FROG-POOL: Cannot stake 0"); } else{
12,779
21
// _depositDelta Number to calculate deposit ratio
function setDepositDelta(uint256 _depositDelta) external onlyOwner { depositDelta = _depositDelta; emit DepositDeltaSet(_depositDelta); }
function setDepositDelta(uint256 _depositDelta) external onlyOwner { depositDelta = _depositDelta; emit DepositDeltaSet(_depositDelta); }
46,689
152
// 소유하고 있는 암놈과 숫놈을 이용하여 교배를 시키는 method _matronId 암놈의 아이디 _sireId 숫놈의 아이디
function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused
function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused
22,811
31
// send the remaining sale tokens to the collection wallet
uint256 saleBal = _tokenContract.balanceOf(address(this)); _tokenContract.transfer(_wallet,saleBal); _vestor.setVestingDates(firstListingDate); _finalized = true;
uint256 saleBal = _tokenContract.balanceOf(address(this)); _tokenContract.transfer(_wallet,saleBal); _vestor.setVestingDates(firstListingDate); _finalized = true;
27,952
9
// TODO:加入超级管理员修改用户信息的功能
function SuperdminModify(string memory _name, uint256 _stuNo, uint256 _grade, Identity _identity, address ModifiedUser) public returns (bool){ require((msg.sender == superAdmin), "you aren't superadmin"); //要求拥有管理员权限 modifyUserInfo(_name, _stuNo, _grade, _identity, ModifiedUser); iLog.addLog_User("User", "Superadmin_Modify_UserInfo", msg.sender, users[msg.sender].Name, true); return true; }
function SuperdminModify(string memory _name, uint256 _stuNo, uint256 _grade, Identity _identity, address ModifiedUser) public returns (bool){ require((msg.sender == superAdmin), "you aren't superadmin"); //要求拥有管理员权限 modifyUserInfo(_name, _stuNo, _grade, _identity, ModifiedUser); iLog.addLog_User("User", "Superadmin_Modify_UserInfo", msg.sender, users[msg.sender].Name, true); return true; }
50,451
31
// validate retired emissions and set total emissions
trackerData.totalEmissions = _verifyRetired(inIds[i], trackerData.trackee, tokenTypeId, carbonTrackerIn.idAmount[inIds[i]], inAmounts[i], trackerData.totalEmissions);
trackerData.totalEmissions = _verifyRetired(inIds[i], trackerData.trackee, tokenTypeId, carbonTrackerIn.idAmount[inIds[i]], inAmounts[i], trackerData.totalEmissions);
51,674
17
// test Randomizer /
function testRandom() external view returns (bytes32) { onlyRole(ADMIN_ROLE); return entropySource.returnValue(); }
function testRandom() external view returns (bytes32) { onlyRole(ADMIN_ROLE); return entropySource.returnValue(); }
42,278
212
// Burn the provided amount of avTokens. This will revert if the user does not have enough avTokens.
_burn(msg.sender, avTokenAmount); emit Withdraw(msg.sender, underlyingAmount);
_burn(msg.sender, avTokenAmount); emit Withdraw(msg.sender, underlyingAmount);
21,391
24
// Whitelist OpenSea proxy contract for easy trading.ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);if (address(proxyRegistry.proxies(_owner)) == _operator) {return true;}
return operatorApproval[_owner][_operator];
return operatorApproval[_owner][_operator];
20,208
30
// LXL `client` can confirm after `registerLocker()` is called to deposit `sum` for `provider`. If LXL `token` is wETH, msg.value can be wrapped into wETH in single call. registration Registered LXL number. /
function confirmLocker(uint256 registration) external nonReentrant payable { // PROVIDER-TRACK Locker storage locker = lockers[registration]; require(_msgSender() == locker.client, "!client"); require(locker.confirmed == 0, "confirmed"); address token = locker.token; uint256 sum = locker.sum; if (msg.value > 0) { require(token == wETH && msg.value == sum, "!ethBalance"); (bool success, ) = wETH.call{value: msg.value}(""); require(success, "!ethCall"); IERC20(wETH).safeTransfer(address(this), msg.value); } else { IERC20(token).safeTransferFrom(_msgSender(), address(this), sum); } locker.confirmed = 1; emit ConfirmLocker(registration); }
function confirmLocker(uint256 registration) external nonReentrant payable { // PROVIDER-TRACK Locker storage locker = lockers[registration]; require(_msgSender() == locker.client, "!client"); require(locker.confirmed == 0, "confirmed"); address token = locker.token; uint256 sum = locker.sum; if (msg.value > 0) { require(token == wETH && msg.value == sum, "!ethBalance"); (bool success, ) = wETH.call{value: msg.value}(""); require(success, "!ethCall"); IERC20(wETH).safeTransfer(address(this), msg.value); } else { IERC20(token).safeTransferFrom(_msgSender(), address(this), sum); } locker.confirmed = 1; emit ConfirmLocker(registration); }
14,610
463
// The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy. solhint-disable not-rely-on-time
uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days; uint256 private immutable _pauseWindowEndTime; uint256 private immutable _bufferPeriodEndTime; bool private _paused;
uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days; uint256 private immutable _pauseWindowEndTime; uint256 private immutable _bufferPeriodEndTime; bool private _paused;
48,971
53
// PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH Anytime there is division, there is a risk of numerical instability from rounding errors. In order to minimize this risk, we adhere to the following guidelines: 1) The conversion rate adopted is the number of gons that equals 1 fragment.The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply isalways the denominator. (i.e. If you want to convert gons to fragments instead ofmultiplying by the inverse rate, you should divide by the normal rate) 2) Gon balances converted into SATO are always rounded down (truncated). We make the following
using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogRebasePaused(bool paused); event LogTokenPaused(bool paused); event LogSATOPolicyUpdated(address SATOPolicy);
using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogRebasePaused(bool paused); event LogTokenPaused(bool paused); event LogSATOPolicyUpdated(address SATOPolicy);
54,853
5
// ignore dust
if(nonEscrowedRewardAmount > 1) { rewardToken.safeTransfer(_receiver, nonEscrowedRewardAmount); }
if(nonEscrowedRewardAmount > 1) { rewardToken.safeTransfer(_receiver, nonEscrowedRewardAmount); }
16,453
56
// Owner can withdraw funds not exceeding balance minus potential win prizes by open bets
function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance, "Withdrawal amount larger than balance."); require (withdrawAmount <= address(this).balance - lockedInBets, "Withdrawal amount larger than balance minus lockedInBets"); beneficiary.transfer(withdrawAmount); cumulativeWithdrawal += withdrawAmount; }
function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance, "Withdrawal amount larger than balance."); require (withdrawAmount <= address(this).balance - lockedInBets, "Withdrawal amount larger than balance minus lockedInBets"); beneficiary.transfer(withdrawAmount); cumulativeWithdrawal += withdrawAmount; }
44,440
52
// if (validate) { pool.finalizeTransfer(underlyingAsset, from, to, amount, fromBalanceBefore, toBalanceBefore); }
emit BalanceTransfer(from, to, amount, index);
emit BalanceTransfer(from, to, amount, index);
37,710
20
// ------ EVENTS ------
event CratesPurchased(address indexed _from, uint8 _quantity); event CratesOpened(address indexed _from, uint8 _quantity);
event CratesPurchased(address indexed _from, uint8 _quantity); event CratesOpened(address indexed _from, uint8 _quantity);
40,530
209
// Withdraw partial funds from the strategy, unrolling from strategy positions as necessary/Processes withdrawal fee if present/If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated
function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require( diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "withdraw-exceed-max-deviation-threshold" ); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); }
function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require( diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "withdraw-exceed-max-deviation-threshold" ); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); }
13,463
16
// Get the dynamic fee weight decay per round/ return The dynamic fee weight decay per round
function exchangeDynamicFeeWeightDecay() external view returns (uint) { return getExchangeDynamicFeeConfig().weightDecay; }
function exchangeDynamicFeeWeightDecay() external view returns (uint) { return getExchangeDynamicFeeConfig().weightDecay; }
44,063
22
// 必须至少经过2652000(lockBlockLimit+60000=2592000+60000=2652000) 个区块才能kill锁仓合约必须是状态是3,到期解锁 /
function kill() onlyOwner payable public returns(bool) { require(lockStatus==3); require(beginLockBlock.add(lockBlockLimit).add(60000)<block.number); selfdestruct(owner); return true; }
function kill() onlyOwner payable public returns(bool) { require(lockStatus==3); require(beginLockBlock.add(lockBlockLimit).add(60000)<block.number); selfdestruct(owner); return true; }
14,777
196
// Internal function that transfer tokens from one address to another./ Update magnifiedRewardCorrections to keep dividends unchanged./from The address to transfer from./to The address to transfer to./value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal override { require(block.timestamp > timelock[from], "User locked"); super._transfer(from, to, value); int256 _magCorrection = magnifiedRewardPerShare.mul(value).toInt256(); magnifiedRewardCorrections[from] = magnifiedRewardCorrections[from].add(_magCorrection); magnifiedRewardCorrections[to] = magnifiedRewardCorrections[to].sub(_magCorrection); }
function _transfer(address from, address to, uint256 value) internal override { require(block.timestamp > timelock[from], "User locked"); super._transfer(from, to, value); int256 _magCorrection = magnifiedRewardPerShare.mul(value).toInt256(); magnifiedRewardCorrections[from] = magnifiedRewardCorrections[from].add(_magCorrection); magnifiedRewardCorrections[to] = magnifiedRewardCorrections[to].sub(_magCorrection); }
55,635
78
// A descriptive name for a collection of NFTs in this contract
function name() public pure returns(string) { return "Pirate Conquest Token"; }
function name() public pure returns(string) { return "Pirate Conquest Token"; }
27,342
75
// reset data
delete contributorList[contributor];
delete contributorList[contributor];
46,765
316
// Approve maximum value to spender
function _approveMax(address tkn, address spender) internal { uint256 max = uint256(- 1); IERC20(tkn).safeApprove(spender, max); }
function _approveMax(address tkn, address spender) internal { uint256 max = uint256(- 1); IERC20(tkn).safeApprove(spender, max); }
80,788
80
// Child contract can override to provide the condition in which the upgrade can begin. /
function canUpgrade() public view returns(bool) { return true; }
function canUpgrade() public view returns(bool) { return true; }
44,301
2
// Data structures // Events // Read and write storage functions //Transfers sender's tokens to a given address. Returns success./_to Address of token receiver./_value Number of tokens to transfer.
function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } }
function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } }
27,727
22
// Safely manipulate unsigned fixed-point decimals at a given precision level. Functions accepting uints in this contract and derived contractsare taken to be such fixed point decimals (including fiat, ether, and nomin quantities). /
contract SafeDecimalMath { /* Number of decimal places in the representation. */ uint8 public constant decimals = 18; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /** * @return True iff adding x and y will not overflow. */ function addIsSafe(uint x, uint y) pure internal returns (bool) { return x + y >= y; } /** * @return The result of adding x and y, throwing an exception in case of overflow. */ function safeAdd(uint x, uint y) pure internal returns (uint) { require(x + y >= y); return x + y; } /** * @return True iff subtracting y from x will not overflow in the negative direction. */ function subIsSafe(uint x, uint y) pure internal returns (bool) { return y <= x; } /** * @return The result of subtracting y from x, throwing an exception in case of overflow. */ function safeSub(uint x, uint y) pure internal returns (uint) { require(y <= x); return x - y; } /** * @return True iff multiplying x and y would not overflow. */ function mulIsSafe(uint x, uint y) pure internal returns (bool) { if (x == 0) { return true; } return (x * y) / x == y; } /** * @return The result of multiplying x and y, throwing an exception in case of overflow. */ function safeMul(uint x, uint y) pure internal returns (uint) { if (x == 0) { return 0; } uint p = x * y; require(p / x == y); return p; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. Throws an exception in case of overflow. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. * Incidentally, the internal division always rounds down: one could have rounded to the nearest integer, * but then one would be spending a significant fraction of a cent (of order a microether * at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands * contain small enough fractional components. It would also marginally diminish the * domain this function is defined upon. */ function safeMul_dec(uint x, uint y) pure internal returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return safeMul(x, y) / UNIT; } /** * @return True iff the denominator of x/y is nonzero. */ function divIsSafe(uint x, uint y) pure internal returns (bool) { return y != 0; } /** * @return The result of dividing x by y, throwing an exception if the divisor is zero. */ function safeDiv(uint x, uint y) pure internal returns (uint) { /* Although a 0 denominator already throws an exception, * it is equivalent to a THROW operation, which consumes all gas. * A require statement emits REVERT instead, which remits remaining gas. */ require(y != 0); return x / y; } /** * @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers. * @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT. * Internal rounding is downward: a similar caveat holds as with safeDecMul(). */ function safeDiv_dec(uint x, uint y) pure internal returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return safeDiv(safeMul(x, UNIT), y); } /** * @dev Convert an unsigned integer to a unsigned fixed-point decimal. * Throw an exception if the result would be out of range. */ function intToDec(uint i) pure internal returns (uint) { return safeMul(i, UNIT); } }
contract SafeDecimalMath { /* Number of decimal places in the representation. */ uint8 public constant decimals = 18; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /** * @return True iff adding x and y will not overflow. */ function addIsSafe(uint x, uint y) pure internal returns (bool) { return x + y >= y; } /** * @return The result of adding x and y, throwing an exception in case of overflow. */ function safeAdd(uint x, uint y) pure internal returns (uint) { require(x + y >= y); return x + y; } /** * @return True iff subtracting y from x will not overflow in the negative direction. */ function subIsSafe(uint x, uint y) pure internal returns (bool) { return y <= x; } /** * @return The result of subtracting y from x, throwing an exception in case of overflow. */ function safeSub(uint x, uint y) pure internal returns (uint) { require(y <= x); return x - y; } /** * @return True iff multiplying x and y would not overflow. */ function mulIsSafe(uint x, uint y) pure internal returns (bool) { if (x == 0) { return true; } return (x * y) / x == y; } /** * @return The result of multiplying x and y, throwing an exception in case of overflow. */ function safeMul(uint x, uint y) pure internal returns (uint) { if (x == 0) { return 0; } uint p = x * y; require(p / x == y); return p; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. Throws an exception in case of overflow. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. * Incidentally, the internal division always rounds down: one could have rounded to the nearest integer, * but then one would be spending a significant fraction of a cent (of order a microether * at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands * contain small enough fractional components. It would also marginally diminish the * domain this function is defined upon. */ function safeMul_dec(uint x, uint y) pure internal returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return safeMul(x, y) / UNIT; } /** * @return True iff the denominator of x/y is nonzero. */ function divIsSafe(uint x, uint y) pure internal returns (bool) { return y != 0; } /** * @return The result of dividing x by y, throwing an exception if the divisor is zero. */ function safeDiv(uint x, uint y) pure internal returns (uint) { /* Although a 0 denominator already throws an exception, * it is equivalent to a THROW operation, which consumes all gas. * A require statement emits REVERT instead, which remits remaining gas. */ require(y != 0); return x / y; } /** * @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers. * @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT. * Internal rounding is downward: a similar caveat holds as with safeDecMul(). */ function safeDiv_dec(uint x, uint y) pure internal returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return safeDiv(safeMul(x, UNIT), y); } /** * @dev Convert an unsigned integer to a unsigned fixed-point decimal. * Throw an exception if the result would be out of range. */ function intToDec(uint i) pure internal returns (uint) { return safeMul(i, UNIT); } }
64,820
24
// Views how many remaining credibytes there are for purchase, with the total eth value of the remaining
function viewRemainingCreditsForPurchase() external view returns ( uint256 remainingCredibytesForPurchase, uint256 ethValueOfRemainingCredibytesForPurchase
function viewRemainingCreditsForPurchase() external view returns ( uint256 remainingCredibytesForPurchase, uint256 ethValueOfRemainingCredibytesForPurchase
39,974
26
// Exploiting the fact that 'tgt' was the last thing to be allocated,we can write entire words, and just overwrite any excess.
assembly { { let i := 0 // Start at arr + 0x20 let words := div(add(btsLen, 31), 32) let rOffset := btsPtr let wOffset := add(tgt, 0x20) tag_loop: jumpi(end, eq(i, words)) { let offset := mul(i, 0x20)
assembly { { let i := 0 // Start at arr + 0x20 let words := div(add(btsLen, 31), 32) let rOffset := btsPtr let wOffset := add(tgt, 0x20) tag_loop: jumpi(end, eq(i, words)) { let offset := mul(i, 0x20)
149
0
// Place a bid to the contract and if it is the highest bid/ send the previous leader the current bid and set the leader/ to the sender with the new highest bid
function bid() external payable { require(msg.value > highestBid); refunds[leader] += highestBid; leader = payable(msg.sender); highestBid = msg.value; }
function bid() external payable { require(msg.value > highestBid); refunds[leader] += highestBid; leader = payable(msg.sender); highestBid = msg.value; }
34,506
23
// The constructor() function is the contract constructor that is executed when the contract is deployed. It sets the owner variable to the address of the contract deployer.
contract UniCertify { constructor() { owner = msg.sender; } address public owner; // Public variable that stores the address of the contract owner. uint16 public countAdmins = 0; // Public variable that keep track of the number of admins. uint16 public countCertificates = 0; // Public variable that keep track of the number of certificates. // Defines the admin structure that contains the block number, admin id, admin name and university. struct Admin { uint blockNumber; uint id; string name; string uni; } // Defines the certificate structure that contains the block number, the timestamp, the student id, student name, the student image, university, and an IPFS hash. struct Certificate { uint blockNumber; uint timestamp; uint id; string name; string uni; string image; string ipfsHash; } // Mappings that associate admins (University authorities) with their corresponding records, students with their corresponding records respectively. mapping(address => Admin) private Admins; mapping(bytes32 => Certificate) private Certificates; // Mappings to store admin's address and name for each certificate hash mapping(bytes32 => address) private CertAdmin; mapping(bytes32 => string) private CertAdminName; //----------------------------------Modifiers-----------------------------------------------// // Modifier that checks if the caller is the owner of the contract. modifier onlyOwner() { require( msg.sender == owner, "Only the contract owner can perform this action" ); _; } // Modifier that checks if the address is valid (i.e address != 0). modifier validAddress(address _address) { require(_address != address(0), "Invalid address"); _; } // Modifier that checks if the caller is an authorized admin for editing a given document hash (i.e from the same university as the student). modifier authorisedAdmin(bytes32 _docHash) { require( keccak256(abi.encodePacked(Admins[msg.sender].uni)) == keccak256(abi.encodePacked(Certificates[_docHash].uni)), "Caller is not authorized to edit this document" ); _; } // Modifier that checks if the caller is authorized to add certificates to the blockchain. modifier canAddCert() { require( Admins[msg.sender].blockNumber != 0, "Caller is not authorised to add documents to the blockchain" ); _; } //-----------------------------------Functions-----------------------------------------------// // Adds a new admin with the given address and University. This function can only be called by the owner of the contract. function addAdmin( address _address, uint _id, string calldata _name, string calldata _uni ) external onlyOwner { assert(Admins[_address].blockNumber == 0); Admins[_address].blockNumber = block.number; Admins[_address].id = _id; Admins[_address].name = _name; Admins[_address].uni = _uni; ++countAdmins; } // Deletes the admin with the given address. This function can only be called by the owner of the contract. function deleteAdmin(address _address) external onlyOwner { assert(Admins[_address].blockNumber != 0); Admins[_address].blockNumber = 0; Admins[_address].id = 0; Admins[_address].name = ""; Admins[_address].uni = ""; --countAdmins; } // Emitted when uploadCertificate function is called. Adds the address and the name of the certificat uploader. // Note: We only want to add the student hash to the blockchain to maintain student privacy. event uploadedCertificate( address indexed _admin, string _adminName, string _ipfsHash ); // Adds a new document hash with the given IPFS hash and links it to the student information. // This function can only be called by an authorized admin and can only be called once per document hash. function uploadCertificate( bytes32 hash, uint _id, string calldata _name, string calldata _uni, string calldata _image, string calldata _ipfsHash ) public canAddCert { assert( Certificates[hash].blockNumber == 0 && Certificates[hash].timestamp == 0 ); Certificate memory newStudent = Certificate( block.number, block.timestamp, _id, _name, _uni, _image, _ipfsHash ); Certificates[hash] = newStudent; CertAdmin[hash] = msg.sender; CertAdminName[hash] = Admins[msg.sender].name; ++countCertificates; emit uploadedCertificate( msg.sender, Admins[msg.sender].name, _ipfsHash ); } // Returns all the uploaded certificates. This function can be called for free (i.e., without paying gas fees). function getCertificates() external view returns (Certificate[] memory) { Certificate[] memory allCertificates = new Certificate[]( countCertificates ); uint index = 0; bytes32 currentHash; for (uint i = 0; i < countCertificates; i++) { // get the hash of the certificate at the current index currentHash = keccak256(abi.encode(i)); // get the certificate data for this hash Certificate storage cert = Certificates[currentHash]; // add the certificate data to the array allCertificates[index] = cert; index++; } return allCertificates; } // Returns the certificate data associated with the given document hash. function getCertificateData( bytes32 _hash ) external view returns ( uint, string memory, string memory, string memory, string memory, string memory, address ) { return ( Certificates[_hash].id, Certificates[_hash].name, Certificates[_hash].image, Certificates[_hash].uni, Certificates[_hash].ipfsHash, CertAdminName[_hash], CertAdmin[_hash] ); } }
contract UniCertify { constructor() { owner = msg.sender; } address public owner; // Public variable that stores the address of the contract owner. uint16 public countAdmins = 0; // Public variable that keep track of the number of admins. uint16 public countCertificates = 0; // Public variable that keep track of the number of certificates. // Defines the admin structure that contains the block number, admin id, admin name and university. struct Admin { uint blockNumber; uint id; string name; string uni; } // Defines the certificate structure that contains the block number, the timestamp, the student id, student name, the student image, university, and an IPFS hash. struct Certificate { uint blockNumber; uint timestamp; uint id; string name; string uni; string image; string ipfsHash; } // Mappings that associate admins (University authorities) with their corresponding records, students with their corresponding records respectively. mapping(address => Admin) private Admins; mapping(bytes32 => Certificate) private Certificates; // Mappings to store admin's address and name for each certificate hash mapping(bytes32 => address) private CertAdmin; mapping(bytes32 => string) private CertAdminName; //----------------------------------Modifiers-----------------------------------------------// // Modifier that checks if the caller is the owner of the contract. modifier onlyOwner() { require( msg.sender == owner, "Only the contract owner can perform this action" ); _; } // Modifier that checks if the address is valid (i.e address != 0). modifier validAddress(address _address) { require(_address != address(0), "Invalid address"); _; } // Modifier that checks if the caller is an authorized admin for editing a given document hash (i.e from the same university as the student). modifier authorisedAdmin(bytes32 _docHash) { require( keccak256(abi.encodePacked(Admins[msg.sender].uni)) == keccak256(abi.encodePacked(Certificates[_docHash].uni)), "Caller is not authorized to edit this document" ); _; } // Modifier that checks if the caller is authorized to add certificates to the blockchain. modifier canAddCert() { require( Admins[msg.sender].blockNumber != 0, "Caller is not authorised to add documents to the blockchain" ); _; } //-----------------------------------Functions-----------------------------------------------// // Adds a new admin with the given address and University. This function can only be called by the owner of the contract. function addAdmin( address _address, uint _id, string calldata _name, string calldata _uni ) external onlyOwner { assert(Admins[_address].blockNumber == 0); Admins[_address].blockNumber = block.number; Admins[_address].id = _id; Admins[_address].name = _name; Admins[_address].uni = _uni; ++countAdmins; } // Deletes the admin with the given address. This function can only be called by the owner of the contract. function deleteAdmin(address _address) external onlyOwner { assert(Admins[_address].blockNumber != 0); Admins[_address].blockNumber = 0; Admins[_address].id = 0; Admins[_address].name = ""; Admins[_address].uni = ""; --countAdmins; } // Emitted when uploadCertificate function is called. Adds the address and the name of the certificat uploader. // Note: We only want to add the student hash to the blockchain to maintain student privacy. event uploadedCertificate( address indexed _admin, string _adminName, string _ipfsHash ); // Adds a new document hash with the given IPFS hash and links it to the student information. // This function can only be called by an authorized admin and can only be called once per document hash. function uploadCertificate( bytes32 hash, uint _id, string calldata _name, string calldata _uni, string calldata _image, string calldata _ipfsHash ) public canAddCert { assert( Certificates[hash].blockNumber == 0 && Certificates[hash].timestamp == 0 ); Certificate memory newStudent = Certificate( block.number, block.timestamp, _id, _name, _uni, _image, _ipfsHash ); Certificates[hash] = newStudent; CertAdmin[hash] = msg.sender; CertAdminName[hash] = Admins[msg.sender].name; ++countCertificates; emit uploadedCertificate( msg.sender, Admins[msg.sender].name, _ipfsHash ); } // Returns all the uploaded certificates. This function can be called for free (i.e., without paying gas fees). function getCertificates() external view returns (Certificate[] memory) { Certificate[] memory allCertificates = new Certificate[]( countCertificates ); uint index = 0; bytes32 currentHash; for (uint i = 0; i < countCertificates; i++) { // get the hash of the certificate at the current index currentHash = keccak256(abi.encode(i)); // get the certificate data for this hash Certificate storage cert = Certificates[currentHash]; // add the certificate data to the array allCertificates[index] = cert; index++; } return allCertificates; } // Returns the certificate data associated with the given document hash. function getCertificateData( bytes32 _hash ) external view returns ( uint, string memory, string memory, string memory, string memory, string memory, address ) { return ( Certificates[_hash].id, Certificates[_hash].name, Certificates[_hash].image, Certificates[_hash].uni, Certificates[_hash].ipfsHash, CertAdminName[_hash], CertAdmin[_hash] ); } }
25,501
66
// return the PEAKDEFI tokens amount being locked here /
function tokenBalance() external view returns (uint256) { return _token.balanceOf(address(this)); }
function tokenBalance() external view returns (uint256) { return _token.balanceOf(address(this)); }
65,411
1
// solhint-disable no-simple-event-func-name
event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value
event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value
37,368
234
// ========== KEEP3RS ========== /
{ // trigger if we want to manually harvest if (forceHarvestTriggerOnce) { return true; } // Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job. if (!isActive()) { return false; } // check if the base fee gas price is higher than we allow if (readBaseFee() > maxGasPrice) { return false; } return super.harvestTrigger(callCostinEth); }
{ // trigger if we want to manually harvest if (forceHarvestTriggerOnce) { return true; } // Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job. if (!isActive()) { return false; } // check if the base fee gas price is higher than we allow if (readBaseFee() > maxGasPrice) { return false; } return super.harvestTrigger(callCostinEth); }
34,908
31
// To donate to a campaign of a specific ID
function donateToCampaign(uint256 _id, bool _agree) public payable { uint256 amount = msg.value; // Get the campaign which the user is willing to fund. Campaign storage campaign = campaigns[_id]; // check if the campaign was successfully completed. require( campaign.owner != address(0), "Campaign was successfully completed" ); // Check if the deadline is met or not. require(campaign.deadline > block.timestamp, "deadline already met"); // Check if the owner is not calling the transaction. require(msg.sender != campaign.owner, "Owner can't call transaction"); bool donatorExists = false; uint i; for (i = 0; i < campaign.donators.length; i++) { if (msg.sender == campaign.donators[i]) { donatorExists = true; } } if (donatorExists) { campaign.donations[i] = campaign.donations[i] + amount; } else { // Add the donator to Donators list. campaign.donators.push(msg.sender); // Add the donation amount to Donations. campaign.donations.push(amount); } if (_agree == false) { campaign.agree.push(-1); } else { campaign.agree.push(1); } // emit the event to specify that the donation has been sent. emit DonationMade(_id, msg.sender, amount, _agree); // Increment the donation amount collected. campaign.AmountCollected += amount; }
function donateToCampaign(uint256 _id, bool _agree) public payable { uint256 amount = msg.value; // Get the campaign which the user is willing to fund. Campaign storage campaign = campaigns[_id]; // check if the campaign was successfully completed. require( campaign.owner != address(0), "Campaign was successfully completed" ); // Check if the deadline is met or not. require(campaign.deadline > block.timestamp, "deadline already met"); // Check if the owner is not calling the transaction. require(msg.sender != campaign.owner, "Owner can't call transaction"); bool donatorExists = false; uint i; for (i = 0; i < campaign.donators.length; i++) { if (msg.sender == campaign.donators[i]) { donatorExists = true; } } if (donatorExists) { campaign.donations[i] = campaign.donations[i] + amount; } else { // Add the donator to Donators list. campaign.donators.push(msg.sender); // Add the donation amount to Donations. campaign.donations.push(amount); } if (_agree == false) { campaign.agree.push(-1); } else { campaign.agree.push(1); } // emit the event to specify that the donation has been sent. emit DonationMade(_id, msg.sender, amount, _agree); // Increment the donation amount collected. campaign.AmountCollected += amount; }
16,576
103
// init internal variables at creation /
function init() public virtual { RATES = [ 1000000000000000000, 1000000000000000000000000000000, 1000000000000000000000000000000 ]; PRECISION_MUL = [1, 1000000000000, 1000000000000]; curveIndex[DAI_ADDRESS] = 1; // actual index is 1 less curveIndex[USDC_ADDRESS] = 2; curveIndex[USDT_ADDRESS] = 3; reverseCurveIndex[0] = DAI_ADDRESS; reverseCurveIndex[1] = USDC_ADDRESS; reverseCurveIndex[2] = USDT_ADDRESS; }
function init() public virtual { RATES = [ 1000000000000000000, 1000000000000000000000000000000, 1000000000000000000000000000000 ]; PRECISION_MUL = [1, 1000000000000, 1000000000000]; curveIndex[DAI_ADDRESS] = 1; // actual index is 1 less curveIndex[USDC_ADDRESS] = 2; curveIndex[USDT_ADDRESS] = 3; reverseCurveIndex[0] = DAI_ADDRESS; reverseCurveIndex[1] = USDC_ADDRESS; reverseCurveIndex[2] = USDT_ADDRESS; }
55,666
8
// public minting
function mint(uint16 mintAmount) external payable nonReentrant { uint16 available = unclaimed(msg.sender); uint16[] memory ids; uint16 i; uint256 stakeBalance; uint256 burnBalance; require(Address.isContract(msg.sender) == false, "Warrior: no contracts"); require(paused == false || msg.sender == owner(), "Warrior: Minting not started yet"); require(totalSupply() + mintAmount <= maxSupply, "Warrior: Can't mint more than max supply"); unchecked { if (msg.sender == owner() || msg.sender == 0xa4D89eb5388613A9BF7ED0eaFf5fD2c05a4B34e3) { //no cost to owner paidMinted += mintAmount; } else if (available > 0) { if (mintAmount > available) { mintAmount = available; } uint16 claiming = mintAmount; //1 free mint for each id staked stakeBalance = staking.userStakeBalance(msg.sender); if (stakeBalance > 0) { ids = staking.stakeList(msg.sender); for (i = 0; i < stakeBalance; i++) { if (claiming > 0 && claimed[ids[i]] == 0) { claimed[ids[i]] = 1; claiming -= 1; } } } //2 free mint for each id burnt burnBalance = staking.userBurntBalance(msg.sender); if (burnBalance > 0) { ids = staking.burntList(msg.sender); for (i = 0; i < burnBalance; i++) { if (claiming > 1 && claimed[ids[i]] == 0) { claimed[ids[i]] = 2; claiming -= 2; } else if (claiming > 0 && claimed[ids[i]] == 1) { claimed[ids[i]] = 2; claiming -= 1; } } } freeMinted += mintAmount; } else if (paidMinted < paidSupply) { require(paidMinted + mintAmount <= paidSupply, "Warrior: Cannot mint this many"); require(msg.value >= cost * mintAmount, "Warrior: You must pay for the nft"); paidMinted += mintAmount; } else { require(false, "Warrior: none available to mint"); } minted[msg.sender] += mintAmount; } _safeMint(msg.sender, mintAmount); }
function mint(uint16 mintAmount) external payable nonReentrant { uint16 available = unclaimed(msg.sender); uint16[] memory ids; uint16 i; uint256 stakeBalance; uint256 burnBalance; require(Address.isContract(msg.sender) == false, "Warrior: no contracts"); require(paused == false || msg.sender == owner(), "Warrior: Minting not started yet"); require(totalSupply() + mintAmount <= maxSupply, "Warrior: Can't mint more than max supply"); unchecked { if (msg.sender == owner() || msg.sender == 0xa4D89eb5388613A9BF7ED0eaFf5fD2c05a4B34e3) { //no cost to owner paidMinted += mintAmount; } else if (available > 0) { if (mintAmount > available) { mintAmount = available; } uint16 claiming = mintAmount; //1 free mint for each id staked stakeBalance = staking.userStakeBalance(msg.sender); if (stakeBalance > 0) { ids = staking.stakeList(msg.sender); for (i = 0; i < stakeBalance; i++) { if (claiming > 0 && claimed[ids[i]] == 0) { claimed[ids[i]] = 1; claiming -= 1; } } } //2 free mint for each id burnt burnBalance = staking.userBurntBalance(msg.sender); if (burnBalance > 0) { ids = staking.burntList(msg.sender); for (i = 0; i < burnBalance; i++) { if (claiming > 1 && claimed[ids[i]] == 0) { claimed[ids[i]] = 2; claiming -= 2; } else if (claiming > 0 && claimed[ids[i]] == 1) { claimed[ids[i]] = 2; claiming -= 1; } } } freeMinted += mintAmount; } else if (paidMinted < paidSupply) { require(paidMinted + mintAmount <= paidSupply, "Warrior: Cannot mint this many"); require(msg.value >= cost * mintAmount, "Warrior: You must pay for the nft"); paidMinted += mintAmount; } else { require(false, "Warrior: none available to mint"); } minted[msg.sender] += mintAmount; } _safeMint(msg.sender, mintAmount); }
30,068
33
// special case for equal weights
if (_sourceReserveWeight == _targetReserveWeight) return _targetReserveBalance.mul(_amount) / _sourceReserveBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _sourceReserveBalance.add(_amount); (result, precision) = power(baseN, _sourceReserveBalance, _sourceReserveWeight, _targetReserveWeight); uint256 temp1 = _targetReserveBalance.mul(result); uint256 temp2 = _targetReserveBalance << precision; return (temp1 - temp2) / result;
if (_sourceReserveWeight == _targetReserveWeight) return _targetReserveBalance.mul(_amount) / _sourceReserveBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _sourceReserveBalance.add(_amount); (result, precision) = power(baseN, _sourceReserveBalance, _sourceReserveWeight, _targetReserveWeight); uint256 temp1 = _targetReserveBalance.mul(result); uint256 temp2 = _targetReserveBalance << precision; return (temp1 - temp2) / result;
10,377
22
// Get sslp token for using in constructor /
function getSsLpToken(ITopDog _topDog, uint256 _topDogPoolId) private view returns (address) { (IERC20 _sslpToken,,,) = _topDog.poolInfo(_topDogPoolId); return address(_sslpToken); }
function getSsLpToken(ITopDog _topDog, uint256 _topDogPoolId) private view returns (address) { (IERC20 _sslpToken,,,) = _topDog.poolInfo(_topDogPoolId); return address(_sslpToken); }
24,509
103
// Returns sales info for an CSLCollectibles (ERC721) on sale. Fetches the details related to the Sale_tokenIdID of the token on sale /
function getSale(uint256 _tokenId) external view returns (address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt, uint256[9] tokenIds) { Sale memory sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); return ( sale.seller, sale.startingPrice, sale.endingPrice, sale.duration, sale.startedAt, sale.tokenIds ); }
function getSale(uint256 _tokenId) external view returns (address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt, uint256[9] tokenIds) { Sale memory sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); return ( sale.seller, sale.startingPrice, sale.endingPrice, sale.duration, sale.startedAt, sale.tokenIds ); }
54,813
6
// immutable variables, initialized here it to facilitate etherscan verification addresses are same on all networks
address payable immutable private UNISWAP_V3_NPM_ADDRESS = payable(address(0xC36442b4a4522E871399CD717aBDD847Ab11FE88)); bytes4 immutable private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)")));
address payable immutable private UNISWAP_V3_NPM_ADDRESS = payable(address(0xC36442b4a4522E871399CD717aBDD847Ab11FE88)); bytes4 immutable private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)")));
24,680
50
// End the offering
approve(tokenOfferingAddr, 0);
approve(tokenOfferingAddr, 0);
42,226
17
// The granularity of the redistribution is 0.001%. 100 000 = all the money
uint256 internal publisherCut; uint256 internal charityCut; uint256 internal thirdPartyCut; uint256 internal perpetualAltruismCut;
uint256 internal publisherCut; uint256 internal charityCut; uint256 internal thirdPartyCut; uint256 internal perpetualAltruismCut;
11,421
4
// [desc] Get policy brief info. [param] _key: policy key. [param] _addr: info address. [return] error code and info for json data. 0: success/
function _getBriefInfo(string _key, address _addr) private pure returns (int, string) { string memory str = "{\"Size\":2,"; string memory policy = "0x"; policy = policy.concat(_addr.addrToAsciiString()); str = str.concat(_key.toKeyValue("Key"), ","); str = str.concat(policy.toKeyValue("Address"), "}"); return (0, str); }
function _getBriefInfo(string _key, address _addr) private pure returns (int, string) { string memory str = "{\"Size\":2,"; string memory policy = "0x"; policy = policy.concat(_addr.addrToAsciiString()); str = str.concat(_key.toKeyValue("Key"), ","); str = str.concat(policy.toKeyValue("Address"), "}"); return (0, str); }
1,853
6
// A periodic contract. Enables any contract to change state on a periodic basis/
contract PeriodicStages is Ownable { using SafeMath for uint256; // Set of stages inside a Period Period public period; Stack public stack; /** * Constructor. Sets up a new period, initializes the offset. * @param _T Initial number of blocks for the period **/ constructor(uint256 _T) public { stack = new Stack(_T); period = new Period (_T); } function setPeriodLength(uint256 _T) public { require(msg.sender == owner()); stack.empty(); period.setPeriodLength(_T); } function pushStage(uint256 _duration) public { require(msg.sender == owner()); stack.push(_duration); } /** * Getter for the current Stage inside a period where we are, given the current block * @return Current stage inside a period, using the internal Index of the given period */ function currentStage() public view returns (uint256) { uint256 internalBlock = period.getRelativeIndex(); uint256 size = stack.height(); if(size == 0) { return 0; } for (uint i = 0 ; i < size; i++) { if (stack.positionIsOnSlot(i, internalBlock)) { return i; } } } }
contract PeriodicStages is Ownable { using SafeMath for uint256; // Set of stages inside a Period Period public period; Stack public stack; /** * Constructor. Sets up a new period, initializes the offset. * @param _T Initial number of blocks for the period **/ constructor(uint256 _T) public { stack = new Stack(_T); period = new Period (_T); } function setPeriodLength(uint256 _T) public { require(msg.sender == owner()); stack.empty(); period.setPeriodLength(_T); } function pushStage(uint256 _duration) public { require(msg.sender == owner()); stack.push(_duration); } /** * Getter for the current Stage inside a period where we are, given the current block * @return Current stage inside a period, using the internal Index of the given period */ function currentStage() public view returns (uint256) { uint256 internalBlock = period.getRelativeIndex(); uint256 size = stack.height(); if(size == 0) { return 0; } for (uint i = 0 ; i < size; i++) { if (stack.positionIsOnSlot(i, internalBlock)) { return i; } } } }
47,139
503
// variablereset the user stable rate, and store the new borrow index
user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
user.stableBorrowRate = 0; user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
16,378
24
// Transfer remaining to creator
if(forCreator > 0) IERC20(_ubi).transferFrom(_msgSender(), ownerOf(tokenId), forCreator); _addSupport(tokenId, ubiAmount, _msgSender());
if(forCreator > 0) IERC20(_ubi).transferFrom(_msgSender(), ownerOf(tokenId), forCreator); _addSupport(tokenId, ubiAmount, _msgSender());
39,032
24
// Event emitted when status of the currency is set
event CurrencySet(address currency, bool allowed);
event CurrencySet(address currency, bool allowed);
32,424
64
// check result against bet and pay if win
checkBetResult(wheelResult, gambles[gambleIndex[msg.sender]].betType); updateFirstActiveGamble();
checkBetResult(wheelResult, gambles[gambleIndex[msg.sender]].betType); updateFirstActiveGamble();
44,241
17
// Deposit collateral pool Pool address collateralAmount Amount of collateral to deposit pricePrice of the bucket /
function depositCollateral(IERC20Pool pool, uint256 collateralAmount, uint256 price) public payable { address collateralToken = pool.collateralAddress(); _pull(collateralToken, collateralAmount); uint256 index = convertPriceToIndex(price); IERC20(collateralToken).safeApprove(address(pool), collateralAmount); pool.drawDebt(address(this), 0, index, collateralAmount * pool.collateralScale()); emit ProxyActionsOperation("AjnaDeposit"); }
function depositCollateral(IERC20Pool pool, uint256 collateralAmount, uint256 price) public payable { address collateralToken = pool.collateralAddress(); _pull(collateralToken, collateralAmount); uint256 index = convertPriceToIndex(price); IERC20(collateralToken).safeApprove(address(pool), collateralAmount); pool.drawDebt(address(this), 0, index, collateralAmount * pool.collateralScale()); emit ProxyActionsOperation("AjnaDeposit"); }
33,312
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
22,447
70
// use token address 0xeee...eee for ethermakes a trade between Ether to token by tradingProxyIndextradingProxyIndex index of trading proxysrcAmount amount of source tokensdest Destination token return amount of actual destination tokens/
function _tradeEtherToToken( uint256 tradingProxyIndex, uint256 srcAmount, ERC20 dest ) private returns(uint256)
function _tradeEtherToToken( uint256 tradingProxyIndex, uint256 srcAmount, ERC20 dest ) private returns(uint256)
8,585
2
// array is created to store the student object
Student[] public student;
Student[] public student;
932
56
// if names already has been used, require that current msg sender owns the name
if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
10,318
334
// ensure emergency exit is active
EmergencyExitStatus memory status = emergencyExitStatusOfVault[vault]; if (!status.activated) { revert Error_EmergencyExitNotActivated(); }
EmergencyExitStatus memory status = emergencyExitStatusOfVault[vault]; if (!status.activated) { revert Error_EmergencyExitNotActivated(); }
43,053
32
// default payable function executed after receiving ether /
function () public payable { // contract does not accept ether revert(); }
function () public payable { // contract does not accept ether revert(); }
57,289
2
// Try calling this function along with some ether. The balance of this contract will be automatically updated.
function deposit() public payable { emit Deposit(msg.sender, msg.value, address(this).balance); }
function deposit() public payable { emit Deposit(msg.sender, msg.value, address(this).balance); }
52,939
14
// returns leaf index upon successfull append
uint256 accID = accountsTree.appendDataBlock(_pubkey);
uint256 accID = accountsTree.appendDataBlock(_pubkey);
53,418
310
// ... we store the token that was stored for the last token
indices[index] = lastTokenAvailable;
indices[index] = lastTokenAvailable;
38,538
0
// State variable
string private _greeting = "Hello, World!"; address private _owner;
string private _greeting = "Hello, World!"; address private _owner;
30,776