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 |
|---|---|---|---|---|
83 | // Function - Uni to buyer/ | function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
| function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
| 27,617 |
218 | // PoLidoNFT interface./2021 ShardLabs | interface IPoLidoNFT is IERC721Upgradeable {
function mint(address _to) external returns (uint256);
function burn(uint256 _tokenId) external;
function isApprovedOrOwner(address _spender, uint256 _tokenId)
external
view
returns (bool);
function setStMATIC(address _stMATIC) external;
function getOwnedTokens(address _address) external view returns (uint256[] memory);
}
| interface IPoLidoNFT is IERC721Upgradeable {
function mint(address _to) external returns (uint256);
function burn(uint256 _tokenId) external;
function isApprovedOrOwner(address _spender, uint256 _tokenId)
external
view
returns (bool);
function setStMATIC(address _stMATIC) external;
function getOwnedTokens(address _address) external view returns (uint256[] memory);
}
| 28,256 |
33 | // /Burn optionTokens and redeemTokens to withdraw underlyingTokens (ethers)./This function is for options with WETH as the underlying asset./ WETH underlyingTokens are converted to ethers before being sent to receiver./ The redeemTokens to burn is equal to the optionTokensstrike ratio./ inputOptions = inputRedeems / strike ratio = outUnderlyings/optionToken The address of the option contract./closeQuantity Quantity of optionTokens to burn and an input to calculate how many redeems to burn./receiver The underlyingTokens (ethers) are sent to the receiver address./ | function safeCloseForETH(
IWETH weth,
IOption optionToken,
uint256 closeQuantity,
address receiver
)
internal
nonZero(closeQuantity)
returns (
uint256,
| function safeCloseForETH(
IWETH weth,
IOption optionToken,
uint256 closeQuantity,
address receiver
)
internal
nonZero(closeQuantity)
returns (
uint256,
| 34,124 |
199 | // Return ProxyAdmin Module address from the Nexusreturn Address of the ProxyAdmin Module contract / | function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
| function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
| 36,019 |
15 | // Retrieve the current fee percentage. A view function that does not modify the state of the contract.return An uint8 representing the fee percentage. / | function feePercentage() public view returns (uint8) {
return UnikuraMothershipStorage.layout()._feePercentage;
}
| function feePercentage() public view returns (uint8) {
return UnikuraMothershipStorage.layout()._feePercentage;
}
| 27,219 |
31 | // stash v3 - set reward hook | function setStashRewardHook(address _stash, address _hook) external onlyOwner{
IOwner(_stash).setRewardHook(_hook);
}
| function setStashRewardHook(address _stash, address _hook) external onlyOwner{
IOwner(_stash).setRewardHook(_hook);
}
| 37,981 |
55 | // if an inverse mapping exists, adjust the price accordingly | InversePricing storage inverse = inversePricing[currencyKey];
if (inverse.entryPoint <= 0) {
return rate;
}
| InversePricing storage inverse = inversePricing[currencyKey];
if (inverse.entryPoint <= 0) {
return rate;
}
| 19,180 |
141 | // Input validation: hE1 |
require(isOnCurve(_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord),
"Point h*E1 is not a valid EC point"
);
require(ecmulVerify(
_cFrag.pointE1.xCoord, // E1_x
|
require(isOnCurve(_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord),
"Point h*E1 is not a valid EC point"
);
require(ecmulVerify(
_cFrag.pointE1.xCoord, // E1_x
| 3,917 |
84 | // Performs division where if there is a modulo, the value is rounded up/ | function divCeil(uint256 a, uint256 b)
internal
pure
returns(uint256)
| function divCeil(uint256 a, uint256 b)
internal
pure
returns(uint256)
| 20,984 |
267 | // Payable fallback to receive and store ETH. Give us tips :) | fallback() external payable {
require(msg.data.length == 0, "fb1");
emit PayableEvent(msg.sender, msg.value);
}
| fallback() external payable {
require(msg.data.length == 0, "fb1");
emit PayableEvent(msg.sender, msg.value);
}
| 20,894 |
59 | // Function to check if an item exists _itemIndex the index of the item _itemCount is the count of that mapping / | function condValidItem(
uint _itemIndex,
uint _itemCount
)
| function condValidItem(
uint _itemIndex,
uint _itemCount
)
| 46,504 |
28 | // exchangeGlobals aren't necessary apart from long calls, but since they are the most expensive transaction we add this overhead to other types of calls, to save gas on long calls. | exchangeGlobals = getExchangeGlobals(_contractAddress, isBuy ? ExchangeType.QUOTE_BASE : ExchangeType.BASE_QUOTE);
pricingGlobals = PricingGlobals({
optionPriceFeeCoefficient: optionPriceFeeCoefficient[_contractAddress],
spotPriceFeeCoefficient: spotPriceFeeCoefficient[_contractAddress],
vegaFeeCoefficient: vegaFeeCoefficient[_contractAddress],
vegaNormFactor: vegaNormFactor[_contractAddress],
standardSize: standardSize[_contractAddress],
skewAdjustmentFactor: skewAdjustmentFactor[_contractAddress],
rateAndCarry: rateAndCarry[_contractAddress],
minDelta: minDelta[_contractAddress],
| exchangeGlobals = getExchangeGlobals(_contractAddress, isBuy ? ExchangeType.QUOTE_BASE : ExchangeType.BASE_QUOTE);
pricingGlobals = PricingGlobals({
optionPriceFeeCoefficient: optionPriceFeeCoefficient[_contractAddress],
spotPriceFeeCoefficient: spotPriceFeeCoefficient[_contractAddress],
vegaFeeCoefficient: vegaFeeCoefficient[_contractAddress],
vegaNormFactor: vegaNormFactor[_contractAddress],
standardSize: standardSize[_contractAddress],
skewAdjustmentFactor: skewAdjustmentFactor[_contractAddress],
rateAndCarry: rateAndCarry[_contractAddress],
minDelta: minDelta[_contractAddress],
| 16,469 |
33 | // Setup liquidity and transfer all amounts according to defined percents, if softcap not reached set Refunded flag/ | function setupLiquidity() public {
require(_isSoldOut == true || block.timestamp > end() , "LaunchpadToken: not sold out or time not elapsed yet" );
require(_isRefunded == false, "Launchpad: refunded is activated");
//
if(_raisedETH < _softCap){
_isRefunded = true;
return;
}
_uniLocked.setupToken(_token);
uint256 ethBalance = address(this).balance;
require(ethBalance > 0, "LaunchpadToken: eth balance needs to be above zero" );
uint256 liquidityAmount = ethBalance.mul(_liquidityPercent).div(_totalPercent);
uint256 tokensAmount = _token.balanceOf(address(this));
require(tokensAmount >= liquidityAmount.mul(_priceUniInv).div(_BASE_PRICE), "Launchpad: Not sufficient tokens amount");
uint256 teamAmount = ethBalance.mul(_teamPercent).div(_totalPercent);
uint256 layerFeeAmount = ethBalance.mul(_fee3).div(_totalPercent);
uint256 supportFeeAmount = ethBalance.mul(_fee1).div(_totalPercent);
uint256 stakeFeeAmount = ethBalance.mul(_fee1).div(_totalPercent);
payable(_layerFeeAddress).transfer(layerFeeAmount);
payable(_supportFeeAddress).transfer(supportFeeAmount);
payable(_stakeFeeAddress).transfer(stakeFeeAmount);
payable(_teamWallet).transfer(teamAmount);
payable(_uniLocked).transfer(liquidityAmount);
_token.safeTransfer(address(_uniLocked), liquidityAmount.mul(_priceUniInv).div(_BASE_PRICE));
_uniLocked.addLiquidity();
_isLiquiditySetup = true;
}
| function setupLiquidity() public {
require(_isSoldOut == true || block.timestamp > end() , "LaunchpadToken: not sold out or time not elapsed yet" );
require(_isRefunded == false, "Launchpad: refunded is activated");
//
if(_raisedETH < _softCap){
_isRefunded = true;
return;
}
_uniLocked.setupToken(_token);
uint256 ethBalance = address(this).balance;
require(ethBalance > 0, "LaunchpadToken: eth balance needs to be above zero" );
uint256 liquidityAmount = ethBalance.mul(_liquidityPercent).div(_totalPercent);
uint256 tokensAmount = _token.balanceOf(address(this));
require(tokensAmount >= liquidityAmount.mul(_priceUniInv).div(_BASE_PRICE), "Launchpad: Not sufficient tokens amount");
uint256 teamAmount = ethBalance.mul(_teamPercent).div(_totalPercent);
uint256 layerFeeAmount = ethBalance.mul(_fee3).div(_totalPercent);
uint256 supportFeeAmount = ethBalance.mul(_fee1).div(_totalPercent);
uint256 stakeFeeAmount = ethBalance.mul(_fee1).div(_totalPercent);
payable(_layerFeeAddress).transfer(layerFeeAmount);
payable(_supportFeeAddress).transfer(supportFeeAmount);
payable(_stakeFeeAddress).transfer(stakeFeeAmount);
payable(_teamWallet).transfer(teamAmount);
payable(_uniLocked).transfer(liquidityAmount);
_token.safeTransfer(address(_uniLocked), liquidityAmount.mul(_priceUniInv).div(_BASE_PRICE));
_uniLocked.addLiquidity();
_isLiquiditySetup = true;
}
| 18,708 |
64 | // Handles the receipt of a multiple ERC1155 token types. This functionis called at the end of a `safeBatchTransferFrom` after the balances havebeen updated. NOTE: To accept the transfer(s), this must return`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`(i.e. 0xbc197c81, or its own function selector). / | function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
| function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
| 27,863 |
35 | // total accrued base rewards for an account | function baseTrackingAccrued(address account) external view returns (uint64);
function baseAccrualScale() external view returns (uint64);
function baseIndexScale() external view returns (uint64);
function factorScale() external view returns (uint64);
function priceScale() external view returns (uint64);
| function baseTrackingAccrued(address account) external view returns (uint64);
function baseAccrualScale() external view returns (uint64);
function baseIndexScale() external view returns (uint64);
function factorScale() external view returns (uint64);
function priceScale() external view returns (uint64);
| 40,623 |
70 | // Generate random number using an address | function random(address address1, uint size) private view returns (uint8) {
return uint8(uint256(keccak256(abi.encodePacked(block.timestamp,
block.difficulty, address1, gasleft()))) % size);
// return uint8(uint256(keccak256(abi.encodePacked(block.difficulty, block.coinbase, address1, gasleft()))) % size);
}
| function random(address address1, uint size) private view returns (uint8) {
return uint8(uint256(keccak256(abi.encodePacked(block.timestamp,
block.difficulty, address1, gasleft()))) % size);
// return uint8(uint256(keccak256(abi.encodePacked(block.difficulty, block.coinbase, address1, gasleft()))) % size);
}
| 11,462 |
113 | // Set the OrderItem typeHash in memory. | mstore(BasicOrder_order_typeHash_ptr, typeHash)
| mstore(BasicOrder_order_typeHash_ptr, typeHash)
| 23,092 |
36 | // called by the owner to unpause, returns to normal state / | function unpause() public onlyAdmin whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
| function unpause() public onlyAdmin whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
| 2,838 |
28 | // Public revoke granted tokens administrative function / | function tokenRevokeTokenGrant(address _token, address _holder, uint256 _grantId) public
ownerExists(msg.sender)
| function tokenRevokeTokenGrant(address _token, address _holder, uint256 _grantId) public
ownerExists(msg.sender)
| 19,006 |
26 | // If `self` starts with `needle`, `needle` is removed from the beginning of `self`. Otherwise, `self` is unmodified. self The slice to operate on. needle The slice to search for.return `self` / | function beyond(slice self, slice needle) internal pure returns (slice) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, length), sha3(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
| function beyond(slice self, slice needle) internal pure returns (slice) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(sha3(selfptr, length), sha3(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
| 18,303 |
15 | // This notifies clients about the amount burnt | event Burn(address indexed from, uint256 value);
| event Burn(address indexed from, uint256 value);
| 65,473 |
78 | // If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault. | if (tokens == totalBondSupply )
return reserveAmount;
| if (tokens == totalBondSupply )
return reserveAmount;
| 35,511 |
85 | // Accrue interest on the cToken and ensure that the operation succeeds. | (bool ok, bytes memory data) = address(cToken).call(abi.encodeWithSelector(
cToken.accrueInterest.selector
));
_checkCompoundInteraction(cToken.accrueInterest.selector, ok, data);
| (bool ok, bytes memory data) = address(cToken).call(abi.encodeWithSelector(
cToken.accrueInterest.selector
));
_checkCompoundInteraction(cToken.accrueInterest.selector, ok, data);
| 67,183 |
159 | // Update speed and emit event | compSupplySpeeds[address(cToken)] = supplySpeed;
emit CompSupplySpeedUpdated(cToken, supplySpeed);
| compSupplySpeeds[address(cToken)] = supplySpeed;
emit CompSupplySpeedUpdated(cToken, supplySpeed);
| 27,473 |
54 | // 返回订单列表@order_type 订单类别 @asset_type 数字资产类别 @money_type 法币资产类别 @length 需要参与排序的订单数 @count 需要返回的订单数@lowmar 最低保证金要求(6位小数) | function sort(bytes32 order_type, bytes32 asset_type, bytes32 money_type, uint256 length,uint256 count,uint256 lowmar) external
| function sort(bytes32 order_type, bytes32 asset_type, bytes32 money_type, uint256 length,uint256 count,uint256 lowmar) external
| 40,807 |
109 | // validate no contract already deployed to the target address. | uint256 codeSize;
| uint256 codeSize;
| 39,186 |
62 | // Gas-optimized reentrancy protection./Modified from OpenZeppelin / (https:github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)/ License-Identifier: MIT | abstract contract ReentrancyGuard {
error Reentrancy();
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private status = NOT_ENTERED;
modifier nonReentrant() {
if (status == ENTERED) revert Reentrancy();
status = ENTERED;
_;
status = NOT_ENTERED;
}
}
| abstract contract ReentrancyGuard {
error Reentrancy();
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private status = NOT_ENTERED;
modifier nonReentrant() {
if (status == ENTERED) revert Reentrancy();
status = ENTERED;
_;
status = NOT_ENTERED;
}
}
| 73,353 |
13 | // Emitted when `indexer` claimed a rebate on `subgraphDeploymentID` during `epoch`related to the `forEpoch` rebate pool.The rebate is for `tokens` amount and `unclaimedAllocationsCount` are left for claimin the rebate pool. `delegationFees` collected and sent to delegation pool. / | event RebateClaimed(
| event RebateClaimed(
| 22,790 |
72 | // Returns the address of the input token / | function getInputToken() public view returns (address) {
return address(brlToken);
}
| function getInputToken() public view returns (address) {
return address(brlToken);
}
| 21,220 |
34 | // used for interacting with uniswap | if (token0 == kassiahotelAddress_) {
isToken0 = true;
} else {
| if (token0 == kassiahotelAddress_) {
isToken0 = true;
} else {
| 12,969 |
171 | // incrementContinuityNumber(): break continuity for _point | function incrementContinuityNumber(uint32 _point)
onlyOwner
external
| function incrementContinuityNumber(uint32 _point)
onlyOwner
external
| 51,152 |
3 | // tokens issued to each account at each generation period | uint256 generationAmount;
| uint256 generationAmount;
| 28,368 |
206 | // For using transferFrom pool (like dodoV1, Curve), pool call transferFrom function to get tokens from adapter | SafeERC20.safeTransfer(IERC20(midToken[i]), curPoolInfo.adapter, curAmount);
| SafeERC20.safeTransfer(IERC20(midToken[i]), curPoolInfo.adapter, curAmount);
| 19,727 |
116 | // Utilized during module initializations to check that the module is in pending stateand that the SetToken is valid / | modifier onlyValidAndPendingSet(ISetToken _setToken) {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
_;
}
| modifier onlyValidAndPendingSet(ISetToken _setToken) {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
_;
}
| 27,560 |
18 | // EVENTS /Fired whenever a new Baller token is created for the first time. | event BallerCreated(uint256 tokenId, string name, address owner);
| event BallerCreated(uint256 tokenId, string name, address owner);
| 29,142 |
100 | // Mapping owner address to token count | mapping (address => uint256) private _balances;
| mapping (address => uint256) private _balances;
| 14,461 |
87 | // IStarNFT Galaxy Protocol Interface for operating with StarNFTs. / | interface IStarNFT is IERC1155 {
/* ============ Events =============== */
// event PowahUpdated(uint256 indexed id, uint256 indexed oldPoints, uint256 indexed newPoints);
/* ============ Functions ============ */
function isOwnerOf(address, uint256) external view returns (bool);
function getNumMinted() external view returns (uint256);
// function starInfo(uint256) external view returns (uint128 powah, uint128 mintBlock, address originator);
// function quasarInfo(uint256) external view returns (uint128 mintBlock, IERC20 stakeToken, uint256 amount, uint256 campaignID);
// function superInfo(uint256) external view returns (uint128 mintBlock, IERC20[] memory stakeToken, uint256[] memory amount, uint256 campaignID);
// mint
function mint(address account, uint256 powah) external returns (uint256);
function mintBatch(address account, uint256 amount, uint256[] calldata powahArr) external returns (uint256[] memory);
function burn(address account, uint256 id) external;
function burnBatch(address account, uint256[] calldata ids) external;
// asset-backing mint
// function mintQuasar(address account, uint256 powah, uint256 cid, IERC20 stakeToken, uint256 amount) external returns (uint256);
// function burnQuasar(address account, uint256 id) external;
// asset-backing forge
// function mintSuper(address account, uint256 powah, uint256 campaignID, IERC20[] calldata stakeTokens, uint256[] calldata amounts) external returns (uint256);
// function burnSuper(address account, uint256 id) external;
// update
// function updatePowah(address owner, uint256 id, uint256 powah) external;
}
| interface IStarNFT is IERC1155 {
/* ============ Events =============== */
// event PowahUpdated(uint256 indexed id, uint256 indexed oldPoints, uint256 indexed newPoints);
/* ============ Functions ============ */
function isOwnerOf(address, uint256) external view returns (bool);
function getNumMinted() external view returns (uint256);
// function starInfo(uint256) external view returns (uint128 powah, uint128 mintBlock, address originator);
// function quasarInfo(uint256) external view returns (uint128 mintBlock, IERC20 stakeToken, uint256 amount, uint256 campaignID);
// function superInfo(uint256) external view returns (uint128 mintBlock, IERC20[] memory stakeToken, uint256[] memory amount, uint256 campaignID);
// mint
function mint(address account, uint256 powah) external returns (uint256);
function mintBatch(address account, uint256 amount, uint256[] calldata powahArr) external returns (uint256[] memory);
function burn(address account, uint256 id) external;
function burnBatch(address account, uint256[] calldata ids) external;
// asset-backing mint
// function mintQuasar(address account, uint256 powah, uint256 cid, IERC20 stakeToken, uint256 amount) external returns (uint256);
// function burnQuasar(address account, uint256 id) external;
// asset-backing forge
// function mintSuper(address account, uint256 powah, uint256 campaignID, IERC20[] calldata stakeTokens, uint256[] calldata amounts) external returns (uint256);
// function burnSuper(address account, uint256 id) external;
// update
// function updatePowah(address owner, uint256 id, uint256 powah) external;
}
| 38,401 |
49 | // Stake by verifier. _chainId chain id. _batchIndex batch index of CTC. _blockNumber block number./ | function verifierStake(uint256 _chainId, uint256 _batchIndex, uint256 _blockNumber) external payable;
| function verifierStake(uint256 _chainId, uint256 _batchIndex, uint256 _blockNumber) external payable;
| 35,224 |
24 | // Look for revert reason and bubble it up if present | if (returndata.length > 0) {
| if (returndata.length > 0) {
| 3,469 |
68 | // no-op, allow even during crowdsale, in order to work around using grantVestedTokens() while in crowdsale | if (_to == msg.sender) return false;
return super.transfer(_to, _value);
| if (_to == msg.sender) return false;
return super.transfer(_to, _value);
| 25,229 |
12 | // Calculate the 10% commission - Dragon Ball Z Hero Owner | uint256 DBZHeroOwnerCommission = (msg.value / 10); // => 10%
| uint256 DBZHeroOwnerCommission = (msg.value / 10); // => 10%
| 44,178 |
520 | // Emit event with old incentive, new incentive | emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
| emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
| 16,413 |
55 | // Limit order Function | function _limitOrder(string memory ticker, uint _amount, uint _price, Side _side) stakeNFTExist(ticker) internal {
bytes32 _ticker = stringToBytes32(ticker);
require(_amount > 0, "Amount can not be 0");
require(_price > 0, "Price can not be 0");
Order[] storage orders = orderBook[_ticker][uint(_side == Side.BUY ? Side.SELL : Side.BUY)];
if(orders.length == 0){
_createOrder(_ticker, _amount, _price, _side);
}
else{
if(_side == Side.BUY){
uint remaining = _amount;
uint i;
uint orderLength = orders.length;
while(i < orders.length && remaining > 0) {
if(_price >= orders[i].price){
remaining = _matchOrder(_ticker,orders, remaining, i, _side);
nextTradeId = nextTradeId.add(1);
if(orders.length.sub(i) == 1 && remaining > 0){
_createOrder(_ticker, remaining, _price, _side);
}
i = i.add(1);
}
else{
i = orderLength;
if(remaining > 0){
_createOrder(_ticker, remaining, _price, _side);
}
}
}
}
if(_side == Side.SELL){
uint remaining = _amount;
uint i;
uint orderLength = orders.length;
while(i < orders.length && remaining > 0) {
if(_price <= orders[i].price){
remaining = _matchOrder(_ticker,orders, remaining, i, _side);
nextTradeId = nextTradeId.add(1);
if(orders.length.sub(i) == 1 && remaining > 0){
_createOrder(_ticker, remaining, _price, _side);
}
i = i.add(1);
}
else{
i = orderLength;
if(remaining > 0){
_createOrder(_ticker, remaining, _price, _side);
}
}
}
}
uint i = 0;
while(i < orders.length && orders[i].filled == orders[i].amount) {
for(uint j = i; j < orders.length.sub(1); j = j.add(1) ) {
orders[j] = orders[j.add(1)];
}
orders.pop();
i = i.add(1);
}
}
}
| function _limitOrder(string memory ticker, uint _amount, uint _price, Side _side) stakeNFTExist(ticker) internal {
bytes32 _ticker = stringToBytes32(ticker);
require(_amount > 0, "Amount can not be 0");
require(_price > 0, "Price can not be 0");
Order[] storage orders = orderBook[_ticker][uint(_side == Side.BUY ? Side.SELL : Side.BUY)];
if(orders.length == 0){
_createOrder(_ticker, _amount, _price, _side);
}
else{
if(_side == Side.BUY){
uint remaining = _amount;
uint i;
uint orderLength = orders.length;
while(i < orders.length && remaining > 0) {
if(_price >= orders[i].price){
remaining = _matchOrder(_ticker,orders, remaining, i, _side);
nextTradeId = nextTradeId.add(1);
if(orders.length.sub(i) == 1 && remaining > 0){
_createOrder(_ticker, remaining, _price, _side);
}
i = i.add(1);
}
else{
i = orderLength;
if(remaining > 0){
_createOrder(_ticker, remaining, _price, _side);
}
}
}
}
if(_side == Side.SELL){
uint remaining = _amount;
uint i;
uint orderLength = orders.length;
while(i < orders.length && remaining > 0) {
if(_price <= orders[i].price){
remaining = _matchOrder(_ticker,orders, remaining, i, _side);
nextTradeId = nextTradeId.add(1);
if(orders.length.sub(i) == 1 && remaining > 0){
_createOrder(_ticker, remaining, _price, _side);
}
i = i.add(1);
}
else{
i = orderLength;
if(remaining > 0){
_createOrder(_ticker, remaining, _price, _side);
}
}
}
}
uint i = 0;
while(i < orders.length && orders[i].filled == orders[i].amount) {
for(uint j = i; j < orders.length.sub(1); j = j.add(1) ) {
orders[j] = orders[j.add(1)];
}
orders.pop();
i = i.add(1);
}
}
}
| 36,768 |
226 | // prettier-ignore solhint-disable-next-line avoid-low-level-calls | (bool success,) = address(this).call{value: msg.value}(data);
| (bool success,) = address(this).call{value: msg.value}(data);
| 77,538 |
31 | // checks if city exists in the contract/ | function cityExist(string city) private returns (bool){
bool cityExists = false;
for (uint256 i; i < cities.length; i++) {
if (equal(cities[i], city)) {
cityExists = true;
break;
}
}
return cityExists;
}
| function cityExist(string city) private returns (bool){
bool cityExists = false;
for (uint256 i; i < cities.length; i++) {
if (equal(cities[i], city)) {
cityExists = true;
break;
}
}
return cityExists;
}
| 22,443 |
155 | // Unstakes LQTY tokens | function _liquityUnstake(Params memory _params) internal returns (uint256) {
uint256 ethGain = LQTYStaking.getPendingETHGain(address(this));
uint256 lusdGain = LQTYStaking.getPendingLUSDGain(address(this));
uint256 staked = LQTYStaking.stakes(address(this));
_params.lqtyAmount = staked > _params.lqtyAmount ? _params.lqtyAmount : staked;
LQTYStaking.unstake(_params.lqtyAmount);
LQTYTokenAddr.withdrawTokens(_params.to, _params.lqtyAmount);
withdrawStaking(ethGain, lusdGain, _params.wethTo, _params.lusdTo);
logger.Log(
address(this),
msg.sender,
"LiquityUnstake",
abi.encode(
_params,
ethGain,
lusdGain
)
);
return _params.lqtyAmount;
}
| function _liquityUnstake(Params memory _params) internal returns (uint256) {
uint256 ethGain = LQTYStaking.getPendingETHGain(address(this));
uint256 lusdGain = LQTYStaking.getPendingLUSDGain(address(this));
uint256 staked = LQTYStaking.stakes(address(this));
_params.lqtyAmount = staked > _params.lqtyAmount ? _params.lqtyAmount : staked;
LQTYStaking.unstake(_params.lqtyAmount);
LQTYTokenAddr.withdrawTokens(_params.to, _params.lqtyAmount);
withdrawStaking(ethGain, lusdGain, _params.wethTo, _params.lusdTo);
logger.Log(
address(this),
msg.sender,
"LiquityUnstake",
abi.encode(
_params,
ethGain,
lusdGain
)
);
return _params.lqtyAmount;
}
| 53,450 |
56 | // Work on a (potentially new) position. Optionally send ETH back to Bank. | function work(uint256 id, address user, uint256 debt, bytes calldata data) external payable;
| function work(uint256 id, address user, uint256 debt, bytes calldata data) external payable;
| 46,691 |
143 | // See {IERC165-supportsInterface}. | function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, IAwooMintableCollection) returns (bool) {
return super.supportsInterface(interfaceId) ||
interfaceId == type(IAwooMintableCollection).interfaceId ||
interfaceId == type(IERC1155).interfaceId ||
interfaceId == ERC1155Supply.totalSupply.selector ||
interfaceId == ERC1155Supply.exists.selector;
}
| function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, IAwooMintableCollection) returns (bool) {
return super.supportsInterface(interfaceId) ||
interfaceId == type(IAwooMintableCollection).interfaceId ||
interfaceId == type(IERC1155).interfaceId ||
interfaceId == ERC1155Supply.totalSupply.selector ||
interfaceId == ERC1155Supply.exists.selector;
}
| 11,081 |
22 | // how many they own | uint256 howMany = ERC721(_collection).balanceOf(_user);
uint256[] memory whichIds = new uint256[](howMany);
| uint256 howMany = ERC721(_collection).balanceOf(_user);
uint256[] memory whichIds = new uint256[](howMany);
| 21,982 |
243 | // Return member address who holds the right to add/remove any member from specific role. | function authorized(uint _memberRoleId) public view returns(address);
| function authorized(uint _memberRoleId) public view returns(address);
| 22,250 |
272 | // rinkeby: 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B | address public LinkToken;
| address public LinkToken;
| 49,131 |
54 | // 不能超出单次最大申购额度 | if (hopeAmount >= maxPurchaseOnce) {
currentAmount = maxPurchaseOnce;
}
| if (hopeAmount >= maxPurchaseOnce) {
currentAmount = maxPurchaseOnce;
}
| 36,771 |
39 | // Whitelist Many user address at once - only Owner can do thisIt will require maximum of 150 addresses to prevent block gas limit max-out and DoS attackIt will add user address in whitelisted mapping / | function whitelistManyUsers(address[] userAddresses) onlyOwner public{
require(whitelistingStatus == true);
uint256 addressCount = userAddresses.length;
require(addressCount <= 150);
for(uint256 i = 0; i < addressCount; i++){
require(userAddresses[i] != 0x0);
whitelisted[userAddresses[i]] = true;
}
}
| function whitelistManyUsers(address[] userAddresses) onlyOwner public{
require(whitelistingStatus == true);
uint256 addressCount = userAddresses.length;
require(addressCount <= 150);
for(uint256 i = 0; i < addressCount; i++){
require(userAddresses[i] != 0x0);
whitelisted[userAddresses[i]] = true;
}
}
| 53,265 |
19 | // Called by the owner to set the _router | function setRouter(address _router) external onlyOwner onlyValidAddress(_router) {
router = _router;
emit SetRouter(msg.sender, _router);
}
| function setRouter(address _router) external onlyOwner onlyValidAddress(_router) {
router = _router;
emit SetRouter(msg.sender, _router);
}
| 8,661 |
4 | // Sends multiple tokens to a single address. _dropId The token id to send. _address The address to receive the tokens. _quantity The amount of tokens to send. / | function batchMint(
uint256 _dropId,
address _address,
uint256 _quantity
| function batchMint(
uint256 _dropId,
address _address,
uint256 _quantity
| 21,349 |
6 | // a list of states that can be transitioned to | bytes32[] nextStates;
| bytes32[] nextStates;
| 22,345 |
84 | // 2 | globals.dailyDataCount,
globals.stakeSharesTotal,
globals.latestStakeId,
_unclaimedSatoshisTotal,
_claimedSatoshisTotal,
_claimedBtcAddrCount,
| globals.dailyDataCount,
globals.stakeSharesTotal,
globals.latestStakeId,
_unclaimedSatoshisTotal,
_claimedSatoshisTotal,
_claimedBtcAddrCount,
| 37,238 |
67 | // Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the revert reason using the provided one. _Available since v4.3._/ | function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
| function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
| 18,093 |
13 | // Swap to supply token if necessary | if ((!supply0 && removedAmount0 > 0) || (supply0 && removedAmount1 > 0)) {
address tokenIn = gUniPool.token1();
address tokenOut = gUniPool.token0();
uint256 amountIn = removedAmount1;
if (!supply0) {
(tokenIn, tokenOut) = (tokenOut, tokenIn);
amountIn = removedAmount0;
}
| if ((!supply0 && removedAmount0 > 0) || (supply0 && removedAmount1 > 0)) {
address tokenIn = gUniPool.token1();
address tokenOut = gUniPool.token0();
uint256 amountIn = removedAmount1;
if (!supply0) {
(tokenIn, tokenOut) = (tokenOut, tokenIn);
amountIn = removedAmount0;
}
| 46,183 |
41 | // check if pot is full, then halt trading | if( _potEthBalance >= _potWinningAmount ) {
uint256 remainingPot = _potEthBalance;
| if( _potEthBalance >= _potWinningAmount ) {
uint256 remainingPot = _potEthBalance;
| 38,346 |
58 | // prevent re-entracy memes; | delete playerRolls[target];
| delete playerRolls[target];
| 35,417 |
49 | // prepare our msg data.by storing this we are able to verify that all admins are approving the same argument input to be executed for the function.we hashit and store in bytes32 so its size is known and comparable | bytes32 _msgData = keccak256(msg.data);
| bytes32 _msgData = keccak256(msg.data);
| 9,046 |
331 | // Yield tracking | uint256 public yieldPerVeFXSStored = 0;
mapping(address => uint256) public userYieldPerTokenPaid;
mapping(address => uint256) public yields;
| uint256 public yieldPerVeFXSStored = 0;
mapping(address => uint256) public userYieldPerTokenPaid;
mapping(address => uint256) public yields;
| 62,233 |
123 | // forgefmt: disable-next-item | result := and(
shr(mul(22, x), 0x375f0016260009d80004ec0002d00001e0000180000180000200000400001),
0x3fffff
)
break
| result := and(
shr(mul(22, x), 0x375f0016260009d80004ec0002d00001e0000180000180000200000400001),
0x3fffff
)
break
| 41,972 |
33 | // ============ Private Functions ============ |
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
|
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
| 2,076 |
75 | // Initialize the extra receivers queue | if (!_queueERInitialized) {
_queueERFirst = 1;
_queueERLast = 0;
_queueERInitialized = true;
| if (!_queueERInitialized) {
_queueERFirst = 1;
_queueERLast = 0;
_queueERInitialized = true;
| 10,196 |
71 | // Give the Captain to &39;_to&39; | captainTokenIdToOwner[_tokenId] = _to;
ownerToCaptainArray[_to].push(_tokenId);
captainIdToOwnerIndex[_tokenId] = ownerToCaptainArray[_to].length - 1;
Transfer(_from != address(0) ? _from : this, _to, _tokenId);
| captainTokenIdToOwner[_tokenId] = _to;
ownerToCaptainArray[_to].push(_tokenId);
captainIdToOwnerIndex[_tokenId] = ownerToCaptainArray[_to].length - 1;
Transfer(_from != address(0) ? _from : this, _to, _tokenId);
| 56,705 |
101 | // 0.03 / hr for first 48 hrs0.01 / hr between 48 - 168 hrs0.05 / hr after 168 hrs / | function timeFactor(address account) public view returns (uint256) {
uint256 avgStakeTime = block.timestamp.sub(getAvgStakeStartTime(account));
uint256 hoursPassedE3 = avgStakeTime.mul(1e3).div(1 hours);
if (hoursPassedE3 <= 0) {
return 1e18;
}
if (hoursPassedE3 <= 48_000) {
return 1e18 + avgStakeTime.mul(3e16).div(1 hours);
}
if (hoursPassedE3 <= 168_000) {
return 244e16 /* 1 + 48 * 0.03 */ + avgStakeTime.sub(48 hours).mul(1e16).div(1 hours);
}
return 364e16 /* 1 + 48 * 0.03 + 120 * 0.01 */ + avgStakeTime.sub(168 hours).mul(5e16).div(1 hours);
}
| function timeFactor(address account) public view returns (uint256) {
uint256 avgStakeTime = block.timestamp.sub(getAvgStakeStartTime(account));
uint256 hoursPassedE3 = avgStakeTime.mul(1e3).div(1 hours);
if (hoursPassedE3 <= 0) {
return 1e18;
}
if (hoursPassedE3 <= 48_000) {
return 1e18 + avgStakeTime.mul(3e16).div(1 hours);
}
if (hoursPassedE3 <= 168_000) {
return 244e16 /* 1 + 48 * 0.03 */ + avgStakeTime.sub(48 hours).mul(1e16).div(1 hours);
}
return 364e16 /* 1 + 48 * 0.03 + 120 * 0.01 */ + avgStakeTime.sub(168 hours).mul(5e16).div(1 hours);
}
| 76,601 |
11 | // ,-.,-.,-. `-'`-'`-' /|\/|\/|\|||,----------. / \/ \/ \ |ERC721Drop| CallerpayoutSplitFundsRecipient`----+-----' || withdraw() || | -------------------------------------------------------------------------> |||| ||||________________________________________________________________________________________________________! ALT/caller is not admin or manager?|| !!_____/|||| !!|revert Access_WithdrawNotAllowed()| !!| <------------------------------------------------------------------------- !!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~!!~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! |||| || send fee amount | || <---------------------------------------------------- |||| |||| ||| ____________________________________________________________ ||| ! ALT/send unsuccesful? ! ||| !_____/|! ||| !|----. ! ||| !|| revert Withdraw_FundsSendFailure()! ||| !|<---' ! ||| !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! ||| !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! |||| ||| send remaining funds amount| ||| <--------------------------- |||| |||| ||| ____________________________________________________________ ||| ! ALT/send unsuccesful? ! ||| !_____/|! ||| !|----. ! ||| !|| revert Withdraw_FundsSendFailure()! ||| !|<---' ! ||| !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! ||| !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! CallerpayoutSplitFundsRecipient,----+-----. ,-.,-.,-. |ERC721Drop| `-'`-'`-' `----------' /|\/|\/|\||| | function withdraw() public {
address[] memory unsorted = getAccounts();
address[] memory accounts = sortAddresses(unsorted);
uint32 numRecipients = uint32(accounts.length);
uint32[] memory percentAllocations = new uint32[](numRecipients);
for (uint256 i = 0; i < numRecipients; ) {
percentAllocations[i] = 1e6 / numRecipients;
unchecked {
++i;
}
}
// atomically deposit funds into split, update recipients to reflect current supercharged NFT holders,
// and distribute
payoutSplit.transfer(address(this).balance);
splitMain.updateAndDistributeETH(
payoutSplit,
accounts,
percentAllocations,
0,
address(0)
);
}
| function withdraw() public {
address[] memory unsorted = getAccounts();
address[] memory accounts = sortAddresses(unsorted);
uint32 numRecipients = uint32(accounts.length);
uint32[] memory percentAllocations = new uint32[](numRecipients);
for (uint256 i = 0; i < numRecipients; ) {
percentAllocations[i] = 1e6 / numRecipients;
unchecked {
++i;
}
}
// atomically deposit funds into split, update recipients to reflect current supercharged NFT holders,
// and distribute
payoutSplit.transfer(address(this).balance);
splitMain.updateAndDistributeETH(
payoutSplit,
accounts,
percentAllocations,
0,
address(0)
);
}
| 971 |
1 | // Emit an event for token metadata reveals/updates, according to EIP-4906._fromTokenId The start token id. _toTokenId The end token id. / | event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
| event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
| 12,408 |
28 | // locate the byte and extract each nibble for the address and the hash. | rightNibbleAddress = uint8(a[i]) % 16;
leftNibbleAddress = (uint8(a[i]) - rightNibbleAddress) / 16;
rightNibbleHash = uint8(b[i]) % 16;
leftNibbleHash = (uint8(b[i]) - rightNibbleHash) / 16;
characterCapitalized[2 * i] = (leftNibbleAddress > 9 && leftNibbleHash > 7);
characterCapitalized[2 * i + 1] = (rightNibbleAddress > 9 && rightNibbleHash > 7);
| rightNibbleAddress = uint8(a[i]) % 16;
leftNibbleAddress = (uint8(a[i]) - rightNibbleAddress) / 16;
rightNibbleHash = uint8(b[i]) % 16;
leftNibbleHash = (uint8(b[i]) - rightNibbleHash) / 16;
characterCapitalized[2 * i] = (leftNibbleAddress > 9 && leftNibbleHash > 7);
characterCapitalized[2 * i + 1] = (rightNibbleAddress > 9 && rightNibbleHash > 7);
| 19,646 |
3 | // Nifty price for public sale | uint256 public constant niftySalePrice = 0.09 ether; // Should we use ether or wei?
| uint256 public constant niftySalePrice = 0.09 ether; // Should we use ether or wei?
| 6,828 |
37 | // User whitelisting functionality//Change whitelisting status on or off When whitelisting is true, then crowdsale will only accept investors who are whitelisted. / | function changeWhitelistingStatus() onlyOwner public{
if (whitelistingStatus == false){
whitelistingStatus = true;
}
else{
whitelistingStatus = false;
}
}
| function changeWhitelistingStatus() onlyOwner public{
if (whitelistingStatus == false){
whitelistingStatus = true;
}
else{
whitelistingStatus = false;
}
}
| 53,263 |
109 | // Emits a {Contribution} event.msg.value is amount to contribute / | function contributeETH() external whenNotPaused nonReentrant payable {
require(WETH == address(contributionToken), "invalid token");
uint256 cAmount = contributeInternal(msg.value);
IWETH(WETH).deposit{value: cAmount}();
| function contributeETH() external whenNotPaused nonReentrant payable {
require(WETH == address(contributionToken), "invalid token");
uint256 cAmount = contributeInternal(msg.value);
IWETH(WETH).deposit{value: cAmount}();
| 16,292 |
16 | // apy setup | uint32 public ubaseApy = 10;
uint32 public globalApy = 100000;
uint16 public halvening = 1;
| uint32 public ubaseApy = 10;
uint32 public globalApy = 100000;
uint16 public halvening = 1;
| 38,598 |
198 | // Send all of our Curve pool tokens to be deposited | uint256 _toInvest = balanceOfWant();
| uint256 _toInvest = balanceOfWant();
| 17,425 |
48 | // Emit Upgrade-event with fail-indication | emit Upgrade(_account, 0);
| emit Upgrade(_account, 0);
| 18,140 |
1 | // Impossible Situation: only owner can execute if state is idle but the BSC position remains. | event ClearBSCState(address indexed lp, address indexed account, uint indexed eventId);
| event ClearBSCState(address indexed lp, address indexed account, uint indexed eventId);
| 41,200 |
52 | // update dividends tracker | int256 _updatedPayouts = (int256) (_taxedEthereum * magnitude);
payoutsTo_[_customerAddress] -= _updatedPayouts;
| int256 _updatedPayouts = (int256) (_taxedEthereum * magnitude);
payoutsTo_[_customerAddress] -= _updatedPayouts;
| 8,248 |
5 | // Guarantees msg.sender is owner of the given auction_auctionId uint ID of the auction to validate its ownership belongs to msg.sender/ | modifier isOwner(uint _auctionId) {
require(auctions[_auctionId].owner == msg.sender);
_;
}
| modifier isOwner(uint _auctionId) {
require(auctions[_auctionId].owner == msg.sender);
_;
}
| 76 |
69 | // Deposit tokens to specific account with time-lock./tokenAddr The contract address of a ERC20/ERC223 token./account The owner of deposited tokens./amount Amount to deposit./releaseTime Time-lock period./ return True if it is successful, revert otherwise. | function depositERC20 (
address tokenAddr,
address account,
uint256 amount,
uint256 releaseTime
) external returns (bool) {
require(account != address(0x0));
require(tokenAddr != 0x0);
require(msg.value == 0);
require(amount > 0);
| function depositERC20 (
address tokenAddr,
address account,
uint256 amount,
uint256 releaseTime
) external returns (bool) {
require(account != address(0x0));
require(tokenAddr != 0x0);
require(msg.value == 0);
require(amount > 0);
| 11,351 |
137 | // Recalc part if needed | if (j + 1 < parts) {
uint256 newRate = reserves[bestIndex](
fromToken,
toToken,
srcAmount.mul(distribution[bestIndex] + 1).div(parts),
flags
);
if (newRate > fullRates[bestIndex]) {
rates[bestIndex] = newRate.sub(fullRates[bestIndex]);
} else {
| if (j + 1 < parts) {
uint256 newRate = reserves[bestIndex](
fromToken,
toToken,
srcAmount.mul(distribution[bestIndex] + 1).div(parts),
flags
);
if (newRate > fullRates[bestIndex]) {
rates[bestIndex] = newRate.sub(fullRates[bestIndex]);
} else {
| 13,860 |
118 | // Uses the Curve protocol to convert the underlying asset into yAsset and then to yCRV./ | function yCurveFromUnderlying() internal {
// convert underlying asset to yAsset
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeApprove(yVault, 0);
IERC20(underlying).safeApprove(yVault, underlyingBalance);
yERC20(yVault).deposit(underlyingBalance);
}
// convert yAsset to yCRV
uint256 yBalance = IERC20(yVault).balanceOf(address(this));
if (yBalance > 0) {
IERC20(yVault).safeApprove(curve, 0);
IERC20(yVault).safeApprove(curve, yBalance);
// we can accept 0 as minimum because this is called only by a trusted role
uint256 minimum = 0;
uint256[4] memory coinAmounts = wrapCoinAmount(yBalance);
ICurveFi(curve).add_liquidity(
coinAmounts, minimum
);
}
// now we have yCRV
}
| function yCurveFromUnderlying() internal {
// convert underlying asset to yAsset
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeApprove(yVault, 0);
IERC20(underlying).safeApprove(yVault, underlyingBalance);
yERC20(yVault).deposit(underlyingBalance);
}
// convert yAsset to yCRV
uint256 yBalance = IERC20(yVault).balanceOf(address(this));
if (yBalance > 0) {
IERC20(yVault).safeApprove(curve, 0);
IERC20(yVault).safeApprove(curve, yBalance);
// we can accept 0 as minimum because this is called only by a trusted role
uint256 minimum = 0;
uint256[4] memory coinAmounts = wrapCoinAmount(yBalance);
ICurveFi(curve).add_liquidity(
coinAmounts, minimum
);
}
// now we have yCRV
}
| 35,252 |
138 | // Event emitted when controlled token is added | event ControlledTokenAdded(ITicket indexed token);
event AwardCaptured(uint256 amount);
| event ControlledTokenAdded(ITicket indexed token);
event AwardCaptured(uint256 amount);
| 49,705 |
8 | // Delists then relists otherwise when purchasing a user could be frontrun if they approved max | uint amount = _delist(_listingId);
uint newListingId = _list(amount, _newCost);
emit PriceChanged(_listingId, newListingId, _newCost);
| uint amount = _delist(_listingId);
uint newListingId = _list(amount, _newCost);
emit PriceChanged(_listingId, newListingId, _newCost);
| 3,766 |
17 | // Transforms `amount` of `token`'s balance in a Two Token Pool from managed into cash. This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` isregistered for that Pool. / | function _twoTokenPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
| function _twoTokenPoolManagedToCash(
bytes32 poolId,
IERC20 token,
uint256 amount
| 12 |
3 | // Implements the credit delegation with ERC712 signature delegator The delegator of the credit delegatee The delegatee that can use the credit value The amount to be delegated deadline The deadline timestamp, type(uint256).max for max deadline v The V signature param s The S signature param r The R signature param / | function delegationWithSig(
address delegator,
address delegatee,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
| function delegationWithSig(
address delegator,
address delegatee,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
| 10,296 |
31 | // check if pool is active and not already up-to-date | if (currentBlockTimestamp > pool.lastRewardTime && pool.lpSupplyWithMultiplier > 0) {
uint256 nbSeconds = currentBlockTimestamp.sub(pool.lastRewardTime);
uint256 tokensReward = nbSeconds.mul(rewardsPerSecond).mul(pool.allocPoint).mul(1e18).div(totalAllocPoint);
return accRewardsPerShare.add(tokensReward.div(pool.lpSupplyWithMultiplier));
}
| if (currentBlockTimestamp > pool.lastRewardTime && pool.lpSupplyWithMultiplier > 0) {
uint256 nbSeconds = currentBlockTimestamp.sub(pool.lastRewardTime);
uint256 tokensReward = nbSeconds.mul(rewardsPerSecond).mul(pool.allocPoint).mul(1e18).div(totalAllocPoint);
return accRewardsPerShare.add(tokensReward.div(pool.lpSupplyWithMultiplier));
}
| 40,856 |
42 | // add authorisation for given key and keyname (internal) | function _addKey(address key, bytes32 keyname) internal {
// add the key as an authorised key
keys[key].index = keyList.length;
keys[key].authorised = true;
keys[key].keyname = keyname;
authorisedKeyCount++;
// add to the key list
keyList.push(key);
// emit event
emit KeyAdded(key, keyname);
}
| function _addKey(address key, bytes32 keyname) internal {
// add the key as an authorised key
keys[key].index = keyList.length;
keys[key].authorised = true;
keys[key].keyname = keyname;
authorisedKeyCount++;
// add to the key list
keyList.push(key);
// emit event
emit KeyAdded(key, keyname);
}
| 37,117 |
6 | // return total amount of tokens | function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
| function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
| 2,092 |
27 | // Change mint reveal status | function setRevealStatus(bool _status) public onlyOwner {
revealed = _status;
}
| function setRevealStatus(bool _status) public onlyOwner {
revealed = _status;
}
| 17,110 |
147 | // Find the highest balanced token to withdraw | for(uint256 i2 = 0; i2 < length; i2++){
if(done[i2] == false){
uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals);
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i2;
}
| for(uint256 i2 = 0; i2 < length; i2++){
if(done[i2] == false){
uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals);
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i2;
}
| 66,115 |
19 | // Not using shareTransfer method to save gas. | uint256 _INVALID = shareToken.getTokenId(_markets[i], 0);
uint256 _NO = shareToken.getTokenId(_markets[i], 1);
uint256 _YES = shareToken.getTokenId(_markets[i], 2);
uint256[] memory _tokenIds = new uint256[](3);
_tokenIds[0] = _INVALID;
_tokenIds[1] = _NO;
_tokenIds[2] = _YES;
address[] memory _shareHolders = new address[](3);
| uint256 _INVALID = shareToken.getTokenId(_markets[i], 0);
uint256 _NO = shareToken.getTokenId(_markets[i], 1);
uint256 _YES = shareToken.getTokenId(_markets[i], 2);
uint256[] memory _tokenIds = new uint256[](3);
_tokenIds[0] = _INVALID;
_tokenIds[1] = _NO;
_tokenIds[2] = _YES;
address[] memory _shareHolders = new address[](3);
| 42,083 |
37 | // ERC721 Public/Get total supply for NFT token / return number of NFT issued | function totalSupply() public view returns (uint) {
uint result = nfts.length;
if (result > 0) {
result = result - 1;
}
return result;
}
| function totalSupply() public view returns (uint) {
uint result = nfts.length;
if (result > 0) {
result = result - 1;
}
return result;
}
| 50,932 |
47 | // Batch token transfer. Used by contract creator to distribute initial tokens to holders | function batchTransfer(address[] _recipients, uint[] _values) public onlyOwner returns (bool) {
require( _recipients.length > 0 && _recipients.length == _values.length);
uint total = 0;
for(uint i = 0; i < _values.length; i++){
total = total.add(_values[i]);
}
require(total <= balances[msg.sender]);
uint64 _now = uint64(now);
for(uint j = 0; j < _recipients.length; j++){
balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]);
transferIns[_recipients[j]].push(transferInStruct(uint128(_values[j]),_now));
Transfer(msg.sender, _recipients[j], _values[j]);
}
balances[msg.sender] = balances[msg.sender].sub(total);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
if(balances[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
return true;
}
| function batchTransfer(address[] _recipients, uint[] _values) public onlyOwner returns (bool) {
require( _recipients.length > 0 && _recipients.length == _values.length);
uint total = 0;
for(uint i = 0; i < _values.length; i++){
total = total.add(_values[i]);
}
require(total <= balances[msg.sender]);
uint64 _now = uint64(now);
for(uint j = 0; j < _recipients.length; j++){
balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]);
transferIns[_recipients[j]].push(transferInStruct(uint128(_values[j]),_now));
Transfer(msg.sender, _recipients[j], _values[j]);
}
balances[msg.sender] = balances[msg.sender].sub(total);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
if(balances[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
return true;
}
| 25,325 |
4 | // Reverts an encoded rich revert reason `errorData`./errorData ABI encoded error data. | function rrevert(bytes memory errorData)
internal
pure
| function rrevert(bytes memory errorData)
internal
pure
| 11,960 |
10 | // Convert amountBase base into quote at the latest oracle price, using only direct sources, updating state if necessary. | function _get(bytes6 base, bytes6 quote, uint256 amountBase, uint256 updateTimeIn)
private
returns (uint amountQuote, uint updateTimeOut)
| function _get(bytes6 base, bytes6 quote, uint256 amountBase, uint256 updateTimeIn)
private
returns (uint amountQuote, uint updateTimeOut)
| 78,884 |
170 | // 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows / | mapping(address => mapping(address => uint256))
public originationFeeBalance;
| mapping(address => mapping(address => uint256))
public originationFeeBalance;
| 12,125 |
2 | // House updated after bet was placed. | require(bet_placed_timestamp > houses[house].last_update_timestamp,
"House updated");
require(amount <= players[msg.sender].balance + msg.value,
"Insufficient funds");
players[msg.sender].balance = players[msg.sender].balance + msg.value - amount;
require(nonce > players[msg.sender].nonce
&& nonce <= players[msg.sender].nonce + 10,
"Nonce");
require(amount >= houses[house].min_bet, "Bet too low");
require(amount * odds <= houses[house].max_loss, "Exceeds max loss");
| require(bet_placed_timestamp > houses[house].last_update_timestamp,
"House updated");
require(amount <= players[msg.sender].balance + msg.value,
"Insufficient funds");
players[msg.sender].balance = players[msg.sender].balance + msg.value - amount;
require(nonce > players[msg.sender].nonce
&& nonce <= players[msg.sender].nonce + 10,
"Nonce");
require(amount >= houses[house].min_bet, "Bet too low");
require(amount * odds <= houses[house].max_loss, "Exceeds max loss");
| 37,818 |
3 | // RevokerVersionUpdated - logs Revoker role version updates oldVersion - The value of the previous revoker role credential newVersion - The value of the updated revoker role credential Event emitted when the version of the revoker role is updated / | event RevokerVersionUpdated(uint256 indexed oldVersion, uint256 indexed newVersion);
| event RevokerVersionUpdated(uint256 indexed oldVersion, uint256 indexed newVersion);
| 30,764 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.