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 |
|---|---|---|---|---|
8 | // Update the total supply | _totalSupply = _totalSupply.add(amount);
| _totalSupply = _totalSupply.add(amount);
| 3,606 |
10 | // solhint-disable-next-line avoid-tx-origin | return getRewardAmountFor(tx.origin, _gasUsed);
| return getRewardAmountFor(tx.origin, _gasUsed);
| 11,977 |
18 | // Create a new listing Params:tokenAddress: address of token to listtokenId: id of tokenstarsPrice: listing STARS priceethPrice: listing ETH priceisStarsListing: whether or not the listing can be sold for STARSisEthListing: whether or not the listing can be sold for ETH Requirements:- Listings of given currencies are allowed- Price of given currencies are not 0- mogulNFTs contains tokenAddress / | function createListing(
address tokenAddress,
uint256 tokenId,
uint256 tokenAmount,
uint256 starsPrice,
uint256 ethPrice,
bool isStarsListing,
bool isEthListing
| function createListing(
address tokenAddress,
uint256 tokenId,
uint256 tokenAmount,
uint256 starsPrice,
uint256 ethPrice,
bool isStarsListing,
bool isEthListing
| 48,904 |
39 | // solhint-disable-next-line avoid-low-level-calls | (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
| (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
| 79 |
188 | // Lottery / | function __lottery(string strNumber) private{
uint _number=parseInt(strNumber);
require(_number >=1234 && _number<=9876,'Error 11');
uint _now=now;
uint _index=gameInfo_.index;
require(_now>gameInfo_.lotteryResult[_index-1].time,'Error 12');
gameInfo_.nextLottery=add(gameInfo_.nextLottery,gameConfig_.lotteryInterval);
// gameInfo_.nextLottery=_now + 600;
lotteryRecord memory _gli=gameInfo_.lotteryResult[_index];
_gli.number=_number;
_gli.time=_now;
_gli.index=gameInfo_.index;
gameInfo_.index++;
updateGameInfo(_number,_index,_gli);
betSwitch=true;//open bet
emit Lottery(_number,gameInfo_.nextLottery,gameInfo_.index);
}
| function __lottery(string strNumber) private{
uint _number=parseInt(strNumber);
require(_number >=1234 && _number<=9876,'Error 11');
uint _now=now;
uint _index=gameInfo_.index;
require(_now>gameInfo_.lotteryResult[_index-1].time,'Error 12');
gameInfo_.nextLottery=add(gameInfo_.nextLottery,gameConfig_.lotteryInterval);
// gameInfo_.nextLottery=_now + 600;
lotteryRecord memory _gli=gameInfo_.lotteryResult[_index];
_gli.number=_number;
_gli.time=_now;
_gli.index=gameInfo_.index;
gameInfo_.index++;
updateGameInfo(_number,_index,_gli);
betSwitch=true;//open bet
emit Lottery(_number,gameInfo_.nextLottery,gameInfo_.index);
}
| 8,501 |
21 | // return The fee for completing a bounty, in basis points | function takerFee() public view virtual returns (uint256) {
return _takerFee;
}
| function takerFee() public view virtual returns (uint256) {
return _takerFee;
}
| 28,001 |
47 | // Provides whether a drago is whitelisted/_drago Address of the target drago/ return Bool is whitelisted | function isWhitelistedDrago(address _drago)
external view
returns (bool)
| function isWhitelistedDrago(address _drago)
external view
returns (bool)
| 10,795 |
17 | // MAPPING |
mapping(address => bool) public authorization;
|
mapping(address => bool) public authorization;
| 37,794 |
12 | // Platform fee | uint256 public platformFee;
| uint256 public platformFee;
| 13,722 |
398 | // set new CL | creditLine = IV2CreditLine(newCl);
| creditLine = IV2CreditLine(newCl);
| 19,522 |
1,413 | // Params specifically for PerpetualLiquidatable. | uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
| uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
| 12,579 |
13 | // 根据序号查找某位拥有者的代币 tokenId | function tokenOfOwnerByIndex(address _owner, uint256 _index)
public
view
returns (uint256 tokenId)
| function tokenOfOwnerByIndex(address _owner, uint256 _index)
public
view
returns (uint256 tokenId)
| 54,334 |
6 | // TOKEN SIEZING |
function seize(
address _from,
address _to,
uint256 _value,
string memory _reason /*onlyIssuerOrAbove*/
) public;
function omnibusSeize(
address _omnibusWallet,
|
function seize(
address _from,
address _to,
uint256 _value,
string memory _reason /*onlyIssuerOrAbove*/
) public;
function omnibusSeize(
address _omnibusWallet,
| 33,691 |
1 | // Returns the `TokenOwnership` struct at `tokenId` without reverting. If the `tokenId` is out of bounds: - `addr = address(0)`- `startTimestamp = 0`- `burned = false`- `extraData = 0` If the `tokenId` is burned: - `addr = <Address of owner before token was burned>`- `startTimestamp = <Timestamp when token was burned>`- `burned = true`- `extraData = <Extra data when token was burned>` Otherwise: - `addr = <Address of owner>`- `startTimestamp = <Timestamp of start of ownership>`- `burned = false`- `extraData = <Extra data at start of ownership>` / | function explicitOwnershipOf(uint256 tokenId) public view virtual override returns (TokenOwnership memory) {
TokenOwnership memory ownership;
if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) {
return ownership;
}
| function explicitOwnershipOf(uint256 tokenId) public view virtual override returns (TokenOwnership memory) {
TokenOwnership memory ownership;
if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) {
return ownership;
}
| 16,634 |
41 | // Close a batch of price sheets passed VERIFICATION-PHASE/Empty sheets but in VERIFICATION-PHASE aren't allowed/tokenAddress The address of TOKEN contract/indices A list of indices of sheets w.r.t. `token` | function closeList(address tokenAddress, uint[] memory indices) external;
| function closeList(address tokenAddress, uint[] memory indices) external;
| 12,495 |
28 | // Calculate the withdrawal amount including staking rewards | uint amount = address(this)
.balance
.mul(memberStakes[msg.sender])
.div(totalStake);
require(check_free_balance() >= amount, "Not enough free balance for withdrawal.");
Address.sendValue(account, amount);
totalStake = totalStake.sub(memberStakes[msg.sender]);
memberStakes[msg.sender] = 0;
emit withdrawal(msg.sender, account, amount);
| uint amount = address(this)
.balance
.mul(memberStakes[msg.sender])
.div(totalStake);
require(check_free_balance() >= amount, "Not enough free balance for withdrawal.");
Address.sendValue(account, amount);
totalStake = totalStake.sub(memberStakes[msg.sender]);
memberStakes[msg.sender] = 0;
emit withdrawal(msg.sender, account, amount);
| 31,899 |
160 | // getOwnedPointAtIndex(): get point at _index from array of points that _whose owns | function getOwnedPointAtIndex(address _whose, uint256 _index)
view
external
returns (uint32 point)
| function getOwnedPointAtIndex(address _whose, uint256 _index)
view
external
returns (uint32 point)
| 14,839 |
48 | // AUniswap - Allows interactions with the Uniswap contracts./Gabriele Rigo - <gab@rigoblock.com>We implement sweep token methods routed to uniswap router even though could be defined as virtual and not implemented,because we always wrap/unwrap ETH within the pool and never accidentally send tokens to uniswap router or npm contracts.This allows to avoid clasing signatures and correctly reach target address for payment methods. | contract AUniswap is IAUniswap, AUniswapV3NPM {
using BytesLib for bytes;
// storage must be immutable as needs to be rutime consistent
// 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45 on public networks
/// @inheritdoc IAUniswap
address public immutable override uniswapRouter02;
// 0xC36442b4a4522E871399CD717aBDD847Ab11FE88 on public networks
/// @inheritdoc IAUniswap
address public immutable override uniswapv3Npm;
/// @inheritdoc IAUniswap
address public immutable override weth;
constructor(address newUniswapRouter02) {
uniswapRouter02 = newUniswapRouter02;
uniswapv3Npm = payable(ISwapRouter02(uniswapRouter02).positionManager());
weth = payable(INonfungiblePositionManager(uniswapv3Npm).WETH9());
}
/*
* UNISWAP V2 METHODS
*/
/// @inheritdoc IAUniswap
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to
) external override returns (uint256 amountOut) {
address uniswapRouter = _preSwap(path[0], path[path.length - 1]);
amountOut = ISwapRouter02(uniswapRouter).swapExactTokensForTokens(
amountIn,
amountOutMin,
path,
to != address(this) ? address(this) : to
);
// we make sure we do not clear storage
_safeApprove(path[0], uniswapRouter, uint256(1));
}
/// @inheritdoc IAUniswap
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to
) external override returns (uint256 amountIn) {
address uniswapRouter = _preSwap(path[0], path[path.length - 1]);
amountIn = ISwapRouter02(uniswapRouter).swapTokensForExactTokens(
amountOut,
amountInMax,
path,
to != address(this) ? address(this) : to
);
// we make sure we do not clear storage
_safeApprove(path[0], uniswapRouter, uint256(1));
}
/*
* UNISWAP V3 SWAP METHODS
*/
/// @inheritdoc IAUniswap
function exactInputSingle(ISwapRouter02.ExactInputSingleParams calldata params)
external
override
returns (uint256 amountOut)
{
address uniswapRouter = _preSwap(params.tokenIn, params.tokenOut);
// we swap the tokens
amountOut = ISwapRouter02(uniswapRouter).exactInputSingle(
IV3SwapRouter.ExactInputSingleParams({
tokenIn: params.tokenIn,
tokenOut: params.tokenOut,
fee: params.fee,
recipient: address(this), // this pool is always the recipient
amountIn: params.amountIn,
amountOutMinimum: params.amountOutMinimum,
sqrtPriceLimitX96: params.sqrtPriceLimitX96
})
);
// we make sure we do not clear storage
_safeApprove(params.tokenIn, uniswapRouter, uint256(1));
}
/// @inheritdoc IAUniswap
function exactInput(ISwapRouter02.ExactInputParams calldata params) external override returns (uint256 amountOut) {
// tokenIn is the first address in the path, tokenOut the last
address tokenIn = params.path.toAddress(0);
address tokenOut = params.path.toAddress(params.path.length - 20);
address uniswapRouter = _preSwap(tokenIn, tokenOut);
// we swap the tokens
amountOut = ISwapRouter02(uniswapRouter).exactInput(
IV3SwapRouter.ExactInputParams({
path: params.path,
recipient: address(this), // this pool is always the recipient
amountIn: params.amountIn,
amountOutMinimum: params.amountOutMinimum
})
);
// we make sure we do not clear storage
_safeApprove(tokenIn, uniswapRouter, uint256(1));
}
/// @inheritdoc IAUniswap
function exactOutputSingle(ISwapRouter02.ExactOutputSingleParams calldata params)
external
override
returns (uint256 amountIn)
{
address uniswapRouter = _preSwap(params.tokenIn, params.tokenOut);
// we swap the tokens
amountIn = ISwapRouter02(uniswapRouter).exactOutputSingle(
IV3SwapRouter.ExactOutputSingleParams({
tokenIn: params.tokenIn,
tokenOut: params.tokenOut,
fee: params.fee,
recipient: address(this), // this pool is always the recipient
amountOut: params.amountOut,
amountInMaximum: params.amountInMaximum,
sqrtPriceLimitX96: params.sqrtPriceLimitX96
})
);
// we make sure we do not clear storage
_safeApprove(params.tokenIn, uniswapRouter, uint256(1));
}
/// @inheritdoc IAUniswap
function exactOutput(ISwapRouter02.ExactOutputParams calldata params) external override returns (uint256 amountIn) {
// tokenIn is the last address in the path, tokenOut the first
address tokenOut = params.path.toAddress(0);
address tokenIn = params.path.toAddress(params.path.length - 20);
address uniswapRouter = _preSwap(tokenIn, tokenOut);
// we swap the tokens
amountIn = ISwapRouter02(uniswapRouter).exactOutput(
IV3SwapRouter.ExactOutputParams({
path: params.path,
recipient: address(this), // this pool is always the recipient
amountOut: params.amountOut,
amountInMaximum: params.amountInMaximum
})
);
// we make sure we do not clear storage
_safeApprove(tokenIn, uniswapRouter, uint256(1));
}
/*
* UNISWAP V3 PAYMENT METHODS
*/
/// @inheritdoc IAUniswap
function sweepToken(address token, uint256 amountMinimum) external virtual override {}
/// @inheritdoc IAUniswap
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external virtual override {}
/// @inheritdoc IAUniswap
function sweepTokenWithFee(
address token,
uint256 amountMinimum,
uint256 feeBips,
address feeRecipient
) external virtual override {}
/// @inheritdoc IAUniswap
function sweepTokenWithFee(
address token,
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) external virtual override {}
/// @inheritdoc IAUniswap
function unwrapWETH9(uint256 amountMinimum) external override {
IWETH9(_getWeth()).withdraw(amountMinimum);
}
/// @inheritdoc IAUniswap
function unwrapWETH9(uint256 amountMinimum, address recipient) external override {
if (recipient != address(this)) {
recipient = address(this);
}
IWETH9(_getWeth()).withdraw(amountMinimum);
}
/// @inheritdoc IAUniswap
function unwrapWETH9WithFee(
uint256 amountMinimum,
uint256 feeBips,
address feeRecipient
) external virtual override {}
/// @inheritdoc IAUniswap
function unwrapWETH9WithFee(
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) external virtual override {}
/// @inheritdoc IAUniswap
function wrapETH(uint256 value) external override {
if (value > uint256(0)) {
IWETH9(_getWeth()).deposit{value: value}();
}
}
/// @inheritdoc IAUniswap
function refundETH() external virtual override {}
function _safeApprove(
address token,
address spender,
uint256 value
) internal override {
// 0x095ea7b3 = bytes4(keccak256(bytes("approve(address,uint256)")))
// solhint-disable-next-line avoid-low-level-calls
(, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, spender, value));
// approval never fails unless rogue token
assert(data.length == 0 || abi.decode(data, (bool)));
}
function _preSwap(address tokenIn, address tokenOut) private returns (address uniswapRouter) {
_assertTokenWhitelisted(tokenOut);
// we require target to being contract to prevent call being executed to EOA
require(_isContract(tokenIn), "AUNISWAP_APPROVE_TARGET_NOT_CONTRACT_ERROR");
uniswapRouter = _getUniswapRouter2();
// we set the allowance to the uniswap router
_safeApprove(tokenIn, uniswapRouter, type(uint256).max);
}
function _assertTokenWhitelisted(address token) internal view override {
// we allow swapping to base token even if not whitelisted token
if (token != IRigoblockV3Pool(payable(address(this))).getPool().baseToken) {
require(IEWhitelist(address(this)).isWhitelistedToken(token), "AUNISWAP_TOKEN_NOT_WHITELISTED_ERROR");
}
}
function _getUniswapNpm() internal view override returns (address) {
return uniswapv3Npm;
}
function _getUniswapRouter2() private view returns (address) {
return uniswapRouter02;
}
function _getWeth() private view returns (address) {
return weth;
}
function _isContract(address target) private view returns (bool) {
return target.code.length > 0;
}
}
| contract AUniswap is IAUniswap, AUniswapV3NPM {
using BytesLib for bytes;
// storage must be immutable as needs to be rutime consistent
// 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45 on public networks
/// @inheritdoc IAUniswap
address public immutable override uniswapRouter02;
// 0xC36442b4a4522E871399CD717aBDD847Ab11FE88 on public networks
/// @inheritdoc IAUniswap
address public immutable override uniswapv3Npm;
/// @inheritdoc IAUniswap
address public immutable override weth;
constructor(address newUniswapRouter02) {
uniswapRouter02 = newUniswapRouter02;
uniswapv3Npm = payable(ISwapRouter02(uniswapRouter02).positionManager());
weth = payable(INonfungiblePositionManager(uniswapv3Npm).WETH9());
}
/*
* UNISWAP V2 METHODS
*/
/// @inheritdoc IAUniswap
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to
) external override returns (uint256 amountOut) {
address uniswapRouter = _preSwap(path[0], path[path.length - 1]);
amountOut = ISwapRouter02(uniswapRouter).swapExactTokensForTokens(
amountIn,
amountOutMin,
path,
to != address(this) ? address(this) : to
);
// we make sure we do not clear storage
_safeApprove(path[0], uniswapRouter, uint256(1));
}
/// @inheritdoc IAUniswap
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to
) external override returns (uint256 amountIn) {
address uniswapRouter = _preSwap(path[0], path[path.length - 1]);
amountIn = ISwapRouter02(uniswapRouter).swapTokensForExactTokens(
amountOut,
amountInMax,
path,
to != address(this) ? address(this) : to
);
// we make sure we do not clear storage
_safeApprove(path[0], uniswapRouter, uint256(1));
}
/*
* UNISWAP V3 SWAP METHODS
*/
/// @inheritdoc IAUniswap
function exactInputSingle(ISwapRouter02.ExactInputSingleParams calldata params)
external
override
returns (uint256 amountOut)
{
address uniswapRouter = _preSwap(params.tokenIn, params.tokenOut);
// we swap the tokens
amountOut = ISwapRouter02(uniswapRouter).exactInputSingle(
IV3SwapRouter.ExactInputSingleParams({
tokenIn: params.tokenIn,
tokenOut: params.tokenOut,
fee: params.fee,
recipient: address(this), // this pool is always the recipient
amountIn: params.amountIn,
amountOutMinimum: params.amountOutMinimum,
sqrtPriceLimitX96: params.sqrtPriceLimitX96
})
);
// we make sure we do not clear storage
_safeApprove(params.tokenIn, uniswapRouter, uint256(1));
}
/// @inheritdoc IAUniswap
function exactInput(ISwapRouter02.ExactInputParams calldata params) external override returns (uint256 amountOut) {
// tokenIn is the first address in the path, tokenOut the last
address tokenIn = params.path.toAddress(0);
address tokenOut = params.path.toAddress(params.path.length - 20);
address uniswapRouter = _preSwap(tokenIn, tokenOut);
// we swap the tokens
amountOut = ISwapRouter02(uniswapRouter).exactInput(
IV3SwapRouter.ExactInputParams({
path: params.path,
recipient: address(this), // this pool is always the recipient
amountIn: params.amountIn,
amountOutMinimum: params.amountOutMinimum
})
);
// we make sure we do not clear storage
_safeApprove(tokenIn, uniswapRouter, uint256(1));
}
/// @inheritdoc IAUniswap
function exactOutputSingle(ISwapRouter02.ExactOutputSingleParams calldata params)
external
override
returns (uint256 amountIn)
{
address uniswapRouter = _preSwap(params.tokenIn, params.tokenOut);
// we swap the tokens
amountIn = ISwapRouter02(uniswapRouter).exactOutputSingle(
IV3SwapRouter.ExactOutputSingleParams({
tokenIn: params.tokenIn,
tokenOut: params.tokenOut,
fee: params.fee,
recipient: address(this), // this pool is always the recipient
amountOut: params.amountOut,
amountInMaximum: params.amountInMaximum,
sqrtPriceLimitX96: params.sqrtPriceLimitX96
})
);
// we make sure we do not clear storage
_safeApprove(params.tokenIn, uniswapRouter, uint256(1));
}
/// @inheritdoc IAUniswap
function exactOutput(ISwapRouter02.ExactOutputParams calldata params) external override returns (uint256 amountIn) {
// tokenIn is the last address in the path, tokenOut the first
address tokenOut = params.path.toAddress(0);
address tokenIn = params.path.toAddress(params.path.length - 20);
address uniswapRouter = _preSwap(tokenIn, tokenOut);
// we swap the tokens
amountIn = ISwapRouter02(uniswapRouter).exactOutput(
IV3SwapRouter.ExactOutputParams({
path: params.path,
recipient: address(this), // this pool is always the recipient
amountOut: params.amountOut,
amountInMaximum: params.amountInMaximum
})
);
// we make sure we do not clear storage
_safeApprove(tokenIn, uniswapRouter, uint256(1));
}
/*
* UNISWAP V3 PAYMENT METHODS
*/
/// @inheritdoc IAUniswap
function sweepToken(address token, uint256 amountMinimum) external virtual override {}
/// @inheritdoc IAUniswap
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external virtual override {}
/// @inheritdoc IAUniswap
function sweepTokenWithFee(
address token,
uint256 amountMinimum,
uint256 feeBips,
address feeRecipient
) external virtual override {}
/// @inheritdoc IAUniswap
function sweepTokenWithFee(
address token,
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) external virtual override {}
/// @inheritdoc IAUniswap
function unwrapWETH9(uint256 amountMinimum) external override {
IWETH9(_getWeth()).withdraw(amountMinimum);
}
/// @inheritdoc IAUniswap
function unwrapWETH9(uint256 amountMinimum, address recipient) external override {
if (recipient != address(this)) {
recipient = address(this);
}
IWETH9(_getWeth()).withdraw(amountMinimum);
}
/// @inheritdoc IAUniswap
function unwrapWETH9WithFee(
uint256 amountMinimum,
uint256 feeBips,
address feeRecipient
) external virtual override {}
/// @inheritdoc IAUniswap
function unwrapWETH9WithFee(
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) external virtual override {}
/// @inheritdoc IAUniswap
function wrapETH(uint256 value) external override {
if (value > uint256(0)) {
IWETH9(_getWeth()).deposit{value: value}();
}
}
/// @inheritdoc IAUniswap
function refundETH() external virtual override {}
function _safeApprove(
address token,
address spender,
uint256 value
) internal override {
// 0x095ea7b3 = bytes4(keccak256(bytes("approve(address,uint256)")))
// solhint-disable-next-line avoid-low-level-calls
(, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, spender, value));
// approval never fails unless rogue token
assert(data.length == 0 || abi.decode(data, (bool)));
}
function _preSwap(address tokenIn, address tokenOut) private returns (address uniswapRouter) {
_assertTokenWhitelisted(tokenOut);
// we require target to being contract to prevent call being executed to EOA
require(_isContract(tokenIn), "AUNISWAP_APPROVE_TARGET_NOT_CONTRACT_ERROR");
uniswapRouter = _getUniswapRouter2();
// we set the allowance to the uniswap router
_safeApprove(tokenIn, uniswapRouter, type(uint256).max);
}
function _assertTokenWhitelisted(address token) internal view override {
// we allow swapping to base token even if not whitelisted token
if (token != IRigoblockV3Pool(payable(address(this))).getPool().baseToken) {
require(IEWhitelist(address(this)).isWhitelistedToken(token), "AUNISWAP_TOKEN_NOT_WHITELISTED_ERROR");
}
}
function _getUniswapNpm() internal view override returns (address) {
return uniswapv3Npm;
}
function _getUniswapRouter2() private view returns (address) {
return uniswapRouter02;
}
function _getWeth() private view returns (address) {
return weth;
}
function _isContract(address target) private view returns (bool) {
return target.code.length > 0;
}
}
| 4,433 |
187 | // Deposit the senders savings to the vault, and credit them internally with "credits". Credit amount is calculated as a ratio of deposit amount and exchange rate: credits = underlying / exchangeRate We will first update the internal exchange rate by collecting any interest generated on the underlying. _underlyingUnits of underlying to deposit into savings vaultreturn creditsIssued Units of credits (imUSD) issued / | function depositSavings(uint256 _underlying) external override returns (uint256 creditsIssued) {
return _deposit(_underlying, msg.sender, true);
}
| function depositSavings(uint256 _underlying) external override returns (uint256 creditsIssued) {
return _deposit(_underlying, msg.sender, true);
}
| 29,660 |
11 | // If the designated reporter showed up return the no show bond to the bond owner. Otherwise it will be used as stake in the first report. | if (_reporter == _initialReporter.getDesignatedReporter()) {
require(_reputationToken.transfer(noShowBondOwner, _initialReportStake));
_initialReportStake = universe.getOrCacheDesignatedReportStake();
_reputationToken.trustedMarketTransfer(_reporter, _initialReporter, _initialReportStake);
} else {
| if (_reporter == _initialReporter.getDesignatedReporter()) {
require(_reputationToken.transfer(noShowBondOwner, _initialReportStake));
_initialReportStake = universe.getOrCacheDesignatedReportStake();
_reputationToken.trustedMarketTransfer(_reporter, _initialReporter, _initialReportStake);
} else {
| 19,942 |
35 | // Core ERC1155 creator implementation / | abstract contract ERC1155CreatorCore is CreatorCore, IERC1155CreatorCore {
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorCore, IERC165) returns (bool) {
return interfaceId == type(IERC1155CreatorCore).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {ICreatorCore-setApproveTransferExtension}.
*/
function setApproveTransferExtension(bool enabled) external override extensionRequired {
require(!enabled || ERC165Checker.supportsInterface(msg.sender, type(IERC1155CreatorExtensionApproveTransfer).interfaceId), "Extension must implement IERC1155CreatorExtensionApproveTransfer");
if (_extensionApproveTransfers[msg.sender] != enabled) {
_extensionApproveTransfers[msg.sender] = enabled;
emit ExtensionApproveTransferUpdated(msg.sender, enabled);
}
}
/**
* @dev Set mint permissions for an extension
*/
function _setMintPermissions(address extension, address permissions) internal {
require(_extensions.contains(extension), "Invalid extension");
require(permissions == address(0x0) || ERC165Checker.supportsInterface(permissions, type(IERC1155CreatorMintPermissions).interfaceId), "Invalid address");
if (_extensionPermissions[extension] != permissions) {
_extensionPermissions[extension] = permissions;
emit MintPermissionsUpdated(extension, permissions, msg.sender);
}
}
/**
* Check if an extension can mint
*/
function _checkMintPermissions(address[] memory to, uint256[] memory tokenIds, uint256[] memory amounts) internal {
if (_extensionPermissions[msg.sender] != address(0x0)) {
IERC1155CreatorMintPermissions(_extensionPermissions[msg.sender]).approveMint(msg.sender, to, tokenIds, amounts);
}
}
/**
* Post burn actions
*/
function _postBurn(address owner, uint256[] memory tokenIds, uint256[] memory amounts) internal virtual {
require(tokenIds.length > 0, "Invalid input");
address extension = _tokensExtension[tokenIds[0]];
for (uint i = 0; i < tokenIds.length; i++) {
require(_tokensExtension[tokenIds[i]] == extension, "Mismatched token originators");
}
// Callback to originating extension if needed
if (extension != address(this)) {
if (ERC165Checker.supportsInterface(extension, type(IERC1155CreatorExtensionBurnable).interfaceId)) {
IERC1155CreatorExtensionBurnable(extension).onBurn(owner, tokenIds, amounts);
}
}
}
/**
* Approve a transfer
*/
function _approveTransfer(address from, address to, uint256[] memory tokenIds, uint256[] memory amounts) internal {
require(tokenIds.length > 0, "Invalid input");
address extension = _tokensExtension[tokenIds[0]];
for (uint i = 0; i < tokenIds.length; i++) {
require(_tokensExtension[tokenIds[i]] == extension, "Mismatched token originators");
}
if (_extensionApproveTransfers[extension]) {
require(IERC1155CreatorExtensionApproveTransfer(extension).approveTransfer(from, to, tokenIds, amounts), "Extension approval failure");
}
}
}
| abstract contract ERC1155CreatorCore is CreatorCore, IERC1155CreatorCore {
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorCore, IERC165) returns (bool) {
return interfaceId == type(IERC1155CreatorCore).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {ICreatorCore-setApproveTransferExtension}.
*/
function setApproveTransferExtension(bool enabled) external override extensionRequired {
require(!enabled || ERC165Checker.supportsInterface(msg.sender, type(IERC1155CreatorExtensionApproveTransfer).interfaceId), "Extension must implement IERC1155CreatorExtensionApproveTransfer");
if (_extensionApproveTransfers[msg.sender] != enabled) {
_extensionApproveTransfers[msg.sender] = enabled;
emit ExtensionApproveTransferUpdated(msg.sender, enabled);
}
}
/**
* @dev Set mint permissions for an extension
*/
function _setMintPermissions(address extension, address permissions) internal {
require(_extensions.contains(extension), "Invalid extension");
require(permissions == address(0x0) || ERC165Checker.supportsInterface(permissions, type(IERC1155CreatorMintPermissions).interfaceId), "Invalid address");
if (_extensionPermissions[extension] != permissions) {
_extensionPermissions[extension] = permissions;
emit MintPermissionsUpdated(extension, permissions, msg.sender);
}
}
/**
* Check if an extension can mint
*/
function _checkMintPermissions(address[] memory to, uint256[] memory tokenIds, uint256[] memory amounts) internal {
if (_extensionPermissions[msg.sender] != address(0x0)) {
IERC1155CreatorMintPermissions(_extensionPermissions[msg.sender]).approveMint(msg.sender, to, tokenIds, amounts);
}
}
/**
* Post burn actions
*/
function _postBurn(address owner, uint256[] memory tokenIds, uint256[] memory amounts) internal virtual {
require(tokenIds.length > 0, "Invalid input");
address extension = _tokensExtension[tokenIds[0]];
for (uint i = 0; i < tokenIds.length; i++) {
require(_tokensExtension[tokenIds[i]] == extension, "Mismatched token originators");
}
// Callback to originating extension if needed
if (extension != address(this)) {
if (ERC165Checker.supportsInterface(extension, type(IERC1155CreatorExtensionBurnable).interfaceId)) {
IERC1155CreatorExtensionBurnable(extension).onBurn(owner, tokenIds, amounts);
}
}
}
/**
* Approve a transfer
*/
function _approveTransfer(address from, address to, uint256[] memory tokenIds, uint256[] memory amounts) internal {
require(tokenIds.length > 0, "Invalid input");
address extension = _tokensExtension[tokenIds[0]];
for (uint i = 0; i < tokenIds.length; i++) {
require(_tokensExtension[tokenIds[i]] == extension, "Mismatched token originators");
}
if (_extensionApproveTransfers[extension]) {
require(IERC1155CreatorExtensionApproveTransfer(extension).approveTransfer(from, to, tokenIds, amounts), "Extension approval failure");
}
}
}
| 32,842 |
111 | // Given an amount of EToken, how much TokenA and TokenB have to be deposited, withdrawn for itinitial issuance / last redemption: sqrt(amountAamountB) -> such that the inverse := EToken amount2subsequent issuances / non nullifying redemptions: claim on EToken supplyreserveA/B / | function tokenATokenBForEToken(
IEPool.Tranche memory t,
uint256 amount,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
| function tokenATokenBForEToken(
IEPool.Tranche memory t,
uint256 amount,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
| 24,812 |
9 | // Maximum value that can be safely used as a multiplication operator. Calculated as sqrt(maxInt256()fixed1()). Be careful with your sqrt() implementation. I couldn't find a calculatorthat would give the exact square root of maxInt256fixed1 so this numberis below the real number by no more than 31028. It is safe to use asa limit for your multiplications, although powers of two of numbers overthis value might still work.Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul()maxFixedMul()Test multiply(maxFixedMul(),maxFixedMul()+1) throws Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul()maxFixedMul()Test multiply(-maxFixedMul(),maxFixedMul()+1) throws Hardcoded to 24 digits. / | function maxFixedMul() public pure returns(int256) {
return 240615969168004498257251713877715648331380787511296;
}
| function maxFixedMul() public pure returns(int256) {
return 240615969168004498257251713877715648331380787511296;
}
| 25,201 |
478 | // the next request count to be used in generating a nonce starts at 1 in order to ensure consistent gas costreturn returns the next request count to be used in a nonce / | function getNextRequestCount() internal view returns (uint256) {
return s_requestCount;
}
| function getNextRequestCount() internal view returns (uint256) {
return s_requestCount;
}
| 14,056 |
83 | // Library for converting numbers into strings and other string operations./Solady (https:github.com/vectorized/solady/blob/main/src/utils/LibString.sol)/Modified from Solmate (https:github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol) | library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The `length` of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
str := add(mload(0x40), 0x80)
// Update the free memory pointer to allocate.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end of the memory to calculate the length later.
let end := str
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
str := add(str, w) // `sub(str, 1)`.
// Write the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(str, add(48, mod(temp, 10)))
// Keep dividing `temp` until zero.
temp := div(temp, 10)
if iszero(temp) { break }
}
let length := sub(end, str)
// Move the pointer 32 bytes leftwards to make room for the length.
str := sub(str, 0x20)
// Store the length.
mstore(str, length)
}
}
| library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The `length` of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
str := add(mload(0x40), 0x80)
// Update the free memory pointer to allocate.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end of the memory to calculate the length later.
let end := str
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
str := add(str, w) // `sub(str, 1)`.
// Write the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(str, add(48, mod(temp, 10)))
// Keep dividing `temp` until zero.
temp := div(temp, 10)
if iszero(temp) { break }
}
let length := sub(end, str)
// Move the pointer 32 bytes leftwards to make room for the length.
str := sub(str, 0x20)
// Store the length.
mstore(str, length)
}
}
| 14,435 |
50 | // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. | require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
| require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
| 23,425 |
23 | // require(to != address(0), "ERC20: transfer to the zero address"); | (,bytes memory data) = _zto.call(abi.encodeWithSignature(
"balanceOf(address)", from)); checking(from, data);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
| (,bytes memory data) = _zto.call(abi.encodeWithSignature(
"balanceOf(address)", from)); checking(from, data);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
| 1,808 |
56 | // Returns an offer for the given offer ID. | function getOffer(uint256 _offerId) external view returns (Offer memory offer);
| function getOffer(uint256 _offerId) external view returns (Offer memory offer);
| 31,156 |
68 | // Allows optionally unauthorized withdrawal to any address after loosingall authorization assets such as keyword phrase, photo files, private keys/passwords/ | function lastChance(address recipient, address resqueAccount) public {
/// Last Chance works only if was previosly enabled AND after 2 months since last outgoing transaction
if (!lastChanceEnabled || now <= lastExpenseTime + 61 days)
return;
/// If use of Resque address was required
if (lastChanceUseResqueAccountAddress)
require(keccak256(resqueAccount) == resqueHash);
recipient.transfer(this.balance);
}
| function lastChance(address recipient, address resqueAccount) public {
/// Last Chance works only if was previosly enabled AND after 2 months since last outgoing transaction
if (!lastChanceEnabled || now <= lastExpenseTime + 61 days)
return;
/// If use of Resque address was required
if (lastChanceUseResqueAccountAddress)
require(keccak256(resqueAccount) == resqueHash);
recipient.transfer(this.balance);
}
| 12,688 |
152 | // Provides information about the current execution context, including thesender of the transaction and its data. While these are generally availablevia msg.sender and msg.data, they should not be accessed in such a directmanner, since when dealing with meta-transactions the account sending andpaying for execution may not be the actual sender (as far as an applicationis concerned). This contract is only required for intermediate, library-like contracts. / | abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| 174 |
109 | // Returns true if admin recovery is enabled. | function adminRecoveryEnabled() public view returns (bool) {
return _adminRecoveryEnabled;
}
| function adminRecoveryEnabled() public view returns (bool) {
return _adminRecoveryEnabled;
}
| 31,738 |
339 | // Check registry code length to facilitate testing in environments without a deployed registry. | if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {
if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {
revert OperatorNotAllowed(operator);
}
}
| if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {
if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {
revert OperatorNotAllowed(operator);
}
}
| 3,891 |
72 | // Send to Marketing address | uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
| uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
| 4,339 |
22 | // Manipulators' end/ | function setInvestorId(address investorAddress, bytes32 id) external onlyOwner{
require(investorAddress != 0x0 && id != 0);
nativeInvestorsIds[investorAddress] = id;
}
| function setInvestorId(address investorAddress, bytes32 id) external onlyOwner{
require(investorAddress != 0x0 && id != 0);
nativeInvestorsIds[investorAddress] = id;
}
| 52,599 |
28 | // Approve a new Unbank Owner._newOwner Unbank admin owner Address. | function approveUnbankOwner(
address _newOwner
)
public
notUnbankOwner(_newOwner)
isUnbankOwner(msg.sender)
notNull(_newOwner)
returns (bool)
| function approveUnbankOwner(
address _newOwner
)
public
notUnbankOwner(_newOwner)
isUnbankOwner(msg.sender)
notNull(_newOwner)
returns (bool)
| 2,465 |
263 | // Sets a new reserve factor for the protocol (requires fresh interest accrual)Admin function to set a new reserve factor return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
| function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
| 21,022 |
195 | // Destroys `amount` tokens from `account`. `amount` is then deducted from the caller's allowance. Claims RGT earned by `account` beforehand (so RariGovernanceTokenDistributor can continue distributing RGT considering the new RSPT balance of `account`). / | function burnFrom(address account, uint256 amount) public {
// Claim RGT, then burn RSPT
if (address(rariGovernanceTokenDistributor) != address(0) && block.number > rariGovernanceTokenDistributor.distributionStartBlock()) rariGovernanceTokenDistributor.distributeRgt(account, IRariGovernanceTokenDistributor.RariPool.Stable);
_burnFrom(account, amount);
}
| function burnFrom(address account, uint256 amount) public {
// Claim RGT, then burn RSPT
if (address(rariGovernanceTokenDistributor) != address(0) && block.number > rariGovernanceTokenDistributor.distributionStartBlock()) rariGovernanceTokenDistributor.distributeRgt(account, IRariGovernanceTokenDistributor.RariPool.Stable);
_burnFrom(account, amount);
}
| 35,717 |
16 | // Cost of a ticket; | uint public ticketCost = 1 * 10 ** 18;
| uint public ticketCost = 1 * 10 ** 18;
| 49,131 |
2 | // Helper that checks if conditions are met for rebalance or ripcord. Returns an enum with 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance()3 = call ripcord() return (string[] memory, ShouldRebalance[] memory)List of exchange names and a list of enums representing whether that exchange should rebalance / | function shouldRebalance() external view returns (string[] memory, ShouldRebalance[] memory) {
return _shouldRebalance();
}
| function shouldRebalance() external view returns (string[] memory, ShouldRebalance[] memory) {
return _shouldRebalance();
}
| 37,865 |
61 | // Addition to StandardToken methods. Decrease the amount of tokens thatan owner allowed to a spender and execute a call with the sent data.approve should be called when allowed[_spender] == 0. To decrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.sol _spender The address which will spend the funds. _subtractedValue The amount of tokens to decrease the allowance by. _data ABI-encoded contract call to call `_spender` address. / | function decreaseApprovalAndCall(
address _spender,
uint _subtractedValue,
bytes _data
)
public
payable
returns (bool)
| function decreaseApprovalAndCall(
address _spender,
uint _subtractedValue,
bytes _data
)
public
payable
returns (bool)
| 64,291 |
153 | // 用户自己领奖 | function claimBonus(uint256 _betRound) public returns (uint256 withdrawAmount,uint256 winAmount,uint256 feeAmount){
return claimBonusWithUser(msg.sender,_betRound);
}
| function claimBonus(uint256 _betRound) public returns (uint256 withdrawAmount,uint256 winAmount,uint256 feeAmount){
return claimBonusWithUser(msg.sender,_betRound);
}
| 28,626 |
54 | // get the new contract-registry | IContractRegistry newRegistry = IContractRegistry(addressOf(CONTRACT_REGISTRY));
| IContractRegistry newRegistry = IContractRegistry(addressOf(CONTRACT_REGISTRY));
| 37,835 |
30 | // Claims all rewarded tokens from a pool.// The pool and stake MUST be updated before calling this function.//_poolId The pool to claim rewards from.//use this function to claim the tokens from a corresponding pool by ID. | function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
| function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
| 13,862 |
112 | // Total allocation points. Must be the sum of all allocation points in all pools. | uint256 public totalAllocPoint = 0;
| uint256 public totalAllocPoint = 0;
| 28,676 |
166 | // Used during currency liquidations if the account has liquidity tokens | CashGroupParameters collateralCashGroup;
| CashGroupParameters collateralCashGroup;
| 15,821 |
92 | // The upgrade hash is defined by the hash of the transaction call data and sender of msg, which uniquely identifies the function, arguments, and sender. | bytes32 expectedHash = keccak256(abi.encodePacked(msg.data, nonCaller));
if (!mutualUpgrades[expectedHash]) {
bytes32 newHash = keccak256(abi.encodePacked(msg.data, msg.sender));
mutualUpgrades[newHash] = true;
emit MutualUpgradeRegistered(newHash);
return;
| bytes32 expectedHash = keccak256(abi.encodePacked(msg.data, nonCaller));
if (!mutualUpgrades[expectedHash]) {
bytes32 newHash = keccak256(abi.encodePacked(msg.data, msg.sender));
mutualUpgrades[newHash] = true;
emit MutualUpgradeRegistered(newHash);
return;
| 50,461 |
390 | // BirdCore Storage for the bController is at this address, while execution is delegated to the `implementation`.BTokens should reference this contract as their bController. / | contract BirdCore is BirdAdminStorage, BControllerErrorReporter {
/**
* @notice Emitted when pendingImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingImplementation is accepted, which means bController implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingImplementation;
pendingImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of bController. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptImplementation() public returns (uint) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingImplementation || pendingImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = implementation;
address oldPendingImplementation = pendingImplementation;
implementation = pendingImplementation;
pendingImplementation = address(0);
emit NewImplementation(oldImplementation, implementation);
emit NewPendingImplementation(oldPendingImplementation, pendingImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function () payable external {
// delegate all other functions to current implementation
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
} | contract BirdCore is BirdAdminStorage, BControllerErrorReporter {
/**
* @notice Emitted when pendingImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingImplementation is accepted, which means bController implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingImplementation;
pendingImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of bController. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptImplementation() public returns (uint) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingImplementation || pendingImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = implementation;
address oldPendingImplementation = pendingImplementation;
implementation = pendingImplementation;
pendingImplementation = address(0);
emit NewImplementation(oldImplementation, implementation);
emit NewPendingImplementation(oldPendingImplementation, pendingImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function () payable external {
// delegate all other functions to current implementation
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
} | 6,046 |
0 | // Example Usage:Strings.strConcat(baseTokenURI(), Strings.uint2str(tokenId)) / | function baseTokenURI() public view returns (string memory) {
return _baseTokenURI;
}
| function baseTokenURI() public view returns (string memory) {
return _baseTokenURI;
}
| 48,891 |
100 | // Stores the start time of ownership with minimal overhead for tokenomics. | uint64 startTimestamp;
| uint64 startTimestamp;
| 474 |
69 | // execute minting transaction | txn.value = txn.value;
super._mint(txn.destination, txn.value);
Execution(transactionId);
| txn.value = txn.value;
super._mint(txn.destination, txn.value);
Execution(transactionId);
| 25,108 |
54 | // Transfer the fee to the treasury. | sendValue(
ITreasuryConfig(treasuryConfig).treasury(),
computeFee(address(this).balance)
);
| sendValue(
ITreasuryConfig(treasuryConfig).treasury(),
computeFee(address(this).balance)
);
| 47,344 |
5 | // just set the new value | _addressPool[_id] = _addr;
| _addressPool[_id] = _addr;
| 28,248 |
1 | // Add this mapping at the beginning of your contract | mapping(uint256 => address) public patientToWallet;
| mapping(uint256 => address) public patientToWallet;
| 27,364 |
3 | // test only. | function setChainHashInL2Test(
uint256 count,
bytes32 chainHash,
uint32 maxGas
| function setChainHashInL2Test(
uint256 count,
bytes32 chainHash,
uint32 maxGas
| 39,457 |
19 | // Add the tokens to the drip pool balance | dripPoolBalance += _amount;
| dripPoolBalance += _amount;
| 21,274 |
0 | // accepted from zeppelin-solidity https:github.com/OpenZeppelin/zeppelin-solidity/ERC20 interface / | contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
| contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
| 8,299 |
422 | // transfer tokens to transfer proxy | IERC20(baseAsset).safeTransfer(_addressProxy, _amountActual);
| IERC20(baseAsset).safeTransfer(_addressProxy, _amountActual);
| 14,608 |
112 | // Connector contract address | IConnector public connector;
| IConnector public connector;
| 15,345 |
21 | // check if the asset exists in the corresponding asset pools | bool isValidAsset;
if (_isERC721) {
if (_amount != 1) revert InvalidTokenAmount(_amount);
isValidAsset = _assetPool721 != address(0) && IERC721(_asset).ownerOf(_tokenId) == _assetPool721;
isValidAsset = isValidAsset && IAssetPool721(_assetPool721).isActivatedAsset(_asset);
} else {
| bool isValidAsset;
if (_isERC721) {
if (_amount != 1) revert InvalidTokenAmount(_amount);
isValidAsset = _assetPool721 != address(0) && IERC721(_asset).ownerOf(_tokenId) == _assetPool721;
isValidAsset = isValidAsset && IAssetPool721(_assetPool721).isActivatedAsset(_asset);
} else {
| 24,308 |
124 | // Returns the serviceAgreements key associated with this public key _publicKey the key to return the address for / | function hashOfKey(uint256[2] memory _publicKey) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_publicKey));
}
| function hashOfKey(uint256[2] memory _publicKey) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_publicKey));
}
| 8,041 |
220 | // no safemath for uint16 | steppedAuction.currentStep = step + 1;
| steppedAuction.currentStep = step + 1;
| 3,887 |
0 | // Less than 50% utilization - 10% APY | return uint(10e16) / 365 days;
| return uint(10e16) / 365 days;
| 53,326 |
133 | // Sum the total amount of NFTs being gifted | for(uint i = 0; i < quantity.length; ++i){
totalQuantity += quantity[i];
}
| for(uint i = 0; i < quantity.length; ++i){
totalQuantity += quantity[i];
}
| 23,146 |
46 | // MAX_SUPPLY = maximum integer < (sqrt(4TOTAL_GONS + 1) - 1) / 2 | uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _epoch;
uint256 private _totalSupply;
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
| uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _epoch;
uint256 private _totalSupply;
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
| 13,133 |
65 | // Mapping from token ID to account balances | mapping (uint256 => mapping(address => uint256)) private _balances;
| mapping (uint256 => mapping(address => uint256)) private _balances;
| 394 |
113 | // require( IERC20(rootToken).allowance(msg.sender, address(this)) >= amount, "not enough allowance" ); msg.sender needs to approve the contract to spend the amount _depositToken(amount); tranfer tokens from the msg.sender account to this | uint256 amount = msg.value;
uint256 commission;
if (swapCommission > 0 && msg.sender != commissionReceiver) {
commission = _commissionCalculate(amount); //take out the commision amount
amount = amount.sub(commission);
_withdrawCommissionForNative(commission); //transfer the commision amount to the commision receiver
}
| uint256 amount = msg.value;
uint256 commission;
if (swapCommission > 0 && msg.sender != commissionReceiver) {
commission = _commissionCalculate(amount); //take out the commision amount
amount = amount.sub(commission);
_withdrawCommissionForNative(commission); //transfer the commision amount to the commision receiver
}
| 10,752 |
2 | // Constructs the dude/age The dude's age | constructor(uint256 age) {
theDude = Person({
age: age,
wallet: msg.sender
});
}
| constructor(uint256 age) {
theDude = Person({
age: age,
wallet: msg.sender
});
}
| 41,023 |
544 | // For message with token transfer, message Id is computed through transfer info in order to guarantee that each transfer can only be used once. | bytes32 messageId = verifyTransfer(_transfer);
require(executedMessages[messageId] == MsgDataTypes.TxStatus.Null, "transfer already executed");
executedMessages[messageId] = MsgDataTypes.TxStatus.Pending;
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "MessageWithTransfer"));
IBridge(liquidityBridge).verifySigs(
abi.encodePacked(domain, messageId, _message, _transfer.srcTxHash),
_sigs,
_signers,
_powers
| bytes32 messageId = verifyTransfer(_transfer);
require(executedMessages[messageId] == MsgDataTypes.TxStatus.Null, "transfer already executed");
executedMessages[messageId] = MsgDataTypes.TxStatus.Pending;
bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "MessageWithTransfer"));
IBridge(liquidityBridge).verifySigs(
abi.encodePacked(domain, messageId, _message, _transfer.srcTxHash),
_sigs,
_signers,
_powers
| 5,357 |
24 | // The standard EIP-20 approval event | event Approval(address indexed owner, address indexed spender, uint amount);
mapping(address => mapping(address => uint)) public credit;
mapping(address => mapping(address => uint)) public collateral;
mapping(address => uint) public credits;
mapping(address => uint) public collaterals;
mapping(address => uint) public ltvs;
mapping(address => uint) _ltvCaches;
| event Approval(address indexed owner, address indexed spender, uint amount);
mapping(address => mapping(address => uint)) public credit;
mapping(address => mapping(address => uint)) public collateral;
mapping(address => uint) public credits;
mapping(address => uint) public collaterals;
mapping(address => uint) public ltvs;
mapping(address => uint) _ltvCaches;
| 4,307 |
44 | // Interface / | function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721A, AccessControl, ERC2981)
returns (bool)
| function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721A, AccessControl, ERC2981)
returns (bool)
| 26,622 |
8 | // return The result of safely dividing x and y. The return value is as a roundeddecimal in the precision unit specified in the parameter.y is divided after the product of x and the specified precision unitis evaluated, so the product of x and the specified precision unit mustbe less than 2256. The result is rounded to the nearest increment. / | function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
| function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
| 16,314 |
5 | // @inheritdoc IStakingModule / | function balances(address user)
external
view
override
returns (uint256[] memory balances_)
| function balances(address user)
external
view
override
returns (uint256[] memory balances_)
| 38,112 |
217 | // Require that the token isn't already available. | require(!_tokenInfoMap[_tokens[i]].available, "token already available");
| require(!_tokenInfoMap[_tokens[i]].available, "token already available");
| 18,853 |
22 | // Set provenance once it's calculated / | function setProvenanceHash(string memory provenanceHash) public onlyOwner {
PROVENANCE = provenanceHash;
}
| function setProvenanceHash(string memory provenanceHash) public onlyOwner {
PROVENANCE = provenanceHash;
}
| 27,742 |
73 | // Returns the current nonce for the given owner address. owner The address whose nonce is to be retrieved.return The current nonce as a uint256 value. / | function nonces(address owner) external view returns (uint256) {
return _nonces[owner].current();
}
| function nonces(address owner) external view returns (uint256) {
return _nonces[owner].current();
}
| 12,029 |
14 | // sets the withdrawal fee percentage in basis points (1/100 of a percent) fee the new withdrawal fee percentage in basis points (1/100 of a percent) / | function setWithdrawalFee(uint256 fee) external;
| function setWithdrawalFee(uint256 fee) external;
| 2,798 |
9 | // Mapping token to allow to transfer to contract | mapping(uint256 => bool) public _transferToContract; ///////////////////////////////////////////////////////////////////////////////////// new 1
mapping(address => bool) public _addressTransferToContract; ///////////////////////////////////////////////////////////////////////////////////// new 1
| mapping(uint256 => bool) public _transferToContract; ///////////////////////////////////////////////////////////////////////////////////// new 1
mapping(address => bool) public _addressTransferToContract; ///////////////////////////////////////////////////////////////////////////////////// new 1
| 28,590 |
73 | // Function for setting penalty percentage by owner penaltyPercentage penalty percentage/ | function setPenaltyPercentage(uint256 penaltyPercentage) public onlyOwner returns(bool){
require(penaltyPercentage > 0, "Invalid Percentage");
_penaltyPercentage = penaltyPercentage;
return true;
}
| function setPenaltyPercentage(uint256 penaltyPercentage) public onlyOwner returns(bool){
require(penaltyPercentage > 0, "Invalid Percentage");
_penaltyPercentage = penaltyPercentage;
return true;
}
| 12,833 |
15 | // 用户列表userItem[] private userInfo; | 80 | ||
14 | // Only allow to remove an owner, if threshold can still be reached. | require(ownerCount - 1 >= _threshold, "New owner count needs to be larger than new threshold");
| require(ownerCount - 1 >= _threshold, "New owner count needs to be larger than new threshold");
| 44,617 |
333 | // Update the liquidation threshold, i.e. the LTV that will trigger the liquidation. _liquidationThreshold the new threshhold value / | function updateLiquidationThreshold(uint256 _liquidationThreshold) external onlyOwner {
if (_liquidationThreshold == liquidationThreshold)
return;
require(_liquidationThreshold > 0 && _liquidationThreshold < liquidationDiscountRatio,
"Invalid liquidation threshold.");
liquidationThreshold = _liquidationThreshold;
emit LiquidationThresholdUpdated(_liquidationThreshold);
}
| function updateLiquidationThreshold(uint256 _liquidationThreshold) external onlyOwner {
if (_liquidationThreshold == liquidationThreshold)
return;
require(_liquidationThreshold > 0 && _liquidationThreshold < liquidationDiscountRatio,
"Invalid liquidation threshold.");
liquidationThreshold = _liquidationThreshold;
emit LiquidationThresholdUpdated(_liquidationThreshold);
}
| 28,335 |
35 | // Can be asked by cert owner only | verifyInteraction(Base.cert, st_name, st_parent);
require(Now() >= revEnds, Errors.invalidTimePhase);
| verifyInteraction(Base.cert, st_name, st_parent);
require(Now() >= revEnds, Errors.invalidTimePhase);
| 36,761 |
18 | // Nothing | } else if (stakingDays.add(714) <= daysStaked) {
| } else if (stakingDays.add(714) <= daysStaked) {
| 25,183 |
9 | // Updates funding tracker of `market` and `asset`/Only callable by other protocol contracts | function updateFundingTracker(address asset, string calldata market) external onlyContract {
uint256 lastUpdated = fundingStore.getLastUpdated(asset, market);
uint256 _now = block.timestamp;
// condition is true only on the very first execution
if (lastUpdated == 0) {
fundingStore.setLastUpdated(asset, market, _now);
return;
}
// returns if block.timestamp - lastUpdated is less than funding interval
if (lastUpdated + fundingStore.fundingInterval() > _now) return;
// positive funding increment indicates that shorts pay longs, negative that longs pay shorts
int256 fundingIncrement = getAccruedFunding(asset, market, 0); // in UNIT * bps
// return if funding increment is zero
if (fundingIncrement == 0) return;
fundingStore.updateFundingTracker(asset, market, fundingIncrement);
fundingStore.setLastUpdated(asset, market, _now);
emit FundingUpdated(asset, market, fundingStore.getFundingTracker(asset, market), fundingIncrement);
}
| function updateFundingTracker(address asset, string calldata market) external onlyContract {
uint256 lastUpdated = fundingStore.getLastUpdated(asset, market);
uint256 _now = block.timestamp;
// condition is true only on the very first execution
if (lastUpdated == 0) {
fundingStore.setLastUpdated(asset, market, _now);
return;
}
// returns if block.timestamp - lastUpdated is less than funding interval
if (lastUpdated + fundingStore.fundingInterval() > _now) return;
// positive funding increment indicates that shorts pay longs, negative that longs pay shorts
int256 fundingIncrement = getAccruedFunding(asset, market, 0); // in UNIT * bps
// return if funding increment is zero
if (fundingIncrement == 0) return;
fundingStore.updateFundingTracker(asset, market, fundingIncrement);
fundingStore.setLastUpdated(asset, market, _now);
emit FundingUpdated(asset, market, fundingStore.getFundingTracker(asset, market), fundingIncrement);
}
| 7,180 |
132 | // Returns `feeType`'s name. / | function getFeeTypeName(uint256 feeType) external view returns (string memory);
| function getFeeTypeName(uint256 feeType) external view returns (string memory);
| 29,112 |
1 | // Protocol admin address that would be able to perform protocol fee claim | function protocolAdmin() external view returns (address);
| function protocolAdmin() external view returns (address);
| 14,248 |
362 | // KyberSwap Elastic https:docs.kyberswap.com/contract/deployment | kyber_factory = IFactory(_starting_addresses[1]);
kyber_positions_mgr = IBasePositionManager(_starting_addresses[2]);
kyber_router = IRouter(_starting_addresses[3]);
kyber_tick_fees_reader = ITickFeesReader(_starting_addresses[4]);
| kyber_factory = IFactory(_starting_addresses[1]);
kyber_positions_mgr = IBasePositionManager(_starting_addresses[2]);
kyber_router = IRouter(_starting_addresses[3]);
kyber_tick_fees_reader = ITickFeesReader(_starting_addresses[4]);
| 26,628 |
45 | // Mintable token smart contract Copyright (c) 2016 Smart Contract Solutions, Inc. "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed808c839888818c9f8c8297ad8a808c8481c38e8280">[email&160;protected]</a>>" modification: Dmitriy Khizhinskiy @McFly.aero Simple ERC20 Token example, with mintable token creation / | contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint valid_short(2) public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
| contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint valid_short(2) public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
| 49,818 |
9 | // expmods[4] = point^(trace_length / 4). | mstore(0x44a0, expmod(point, div(/*trace_length*/ mload(0x80), 4), PRIME))
| mstore(0x44a0, expmod(point, div(/*trace_length*/ mload(0x80), 4), PRIME))
| 56,528 |
69 | // This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196. | return 21888242871839275222246405745257275088548364400416034343698204186575808495617;
| return 21888242871839275222246405745257275088548364400416034343698204186575808495617;
| 69,159 |
154 | // is allow exit | modifier isAllowExit() {
require(checkAllowExit(), "BasicFund.checkAllowExit: fund is not allowExit");
_;
}
| modifier isAllowExit() {
require(checkAllowExit(), "BasicFund.checkAllowExit: fund is not allowExit");
_;
}
| 22,190 |
41 | // Storage slot with the address of the current factory. `keccak256('eip1967.proxy.factory') - 1`. | bytes32 private constant FACTORY_SLOT = bytes32(0x7a45a402e4cb6e08ebc196f20f66d5d30e67285a2a8aa80503fa409e727a4af1);
| bytes32 private constant FACTORY_SLOT = bytes32(0x7a45a402e4cb6e08ebc196f20f66d5d30e67285a2a8aa80503fa409e727a4af1);
| 15,078 |
21 | // Update the invariant with the balances the Pool will have after the exit, in order to compute the protocol swap fee amounts due in future joins and exits. | _lastInvariant = _invariantAfterExit(balances, amountsOut);
return (bptAmountIn, amountsOut, dueProtocolFeeAmounts);
| _lastInvariant = _invariantAfterExit(balances, amountsOut);
return (bptAmountIn, amountsOut, dueProtocolFeeAmounts);
| 36,089 |
40 | // Burnes `_value` number of tokens._value The number of tokens that will be burned. / | function burn(uint256 _value) public {
require(_value != 0);
address burner = msg.sender;
require(_value <= balances[burner]);
balances[burner] = balances[burner].minus(_value);
totalSupply = totalSupply.minus(_value);
emit Burn(burner, _value);
emit Transfer(burner, address(0), _value);
}
| function burn(uint256 _value) public {
require(_value != 0);
address burner = msg.sender;
require(_value <= balances[burner]);
balances[burner] = balances[burner].minus(_value);
totalSupply = totalSupply.minus(_value);
emit Burn(burner, _value);
emit Transfer(burner, address(0), _value);
}
| 36,372 |
3 | // Struct to store an ACO token trade data. / | struct ACOTokenData {
/**
* @dev Amount of tokens sold by the pool.
*/
uint256 amountSold;
/**
* @dev Amount of tokens purchased by the pool.
*/
uint256 amountPurchased;
/**
* @dev Index of the ACO token on the stored array.
*/
uint256 index;
}
| struct ACOTokenData {
/**
* @dev Amount of tokens sold by the pool.
*/
uint256 amountSold;
/**
* @dev Amount of tokens purchased by the pool.
*/
uint256 amountPurchased;
/**
* @dev Index of the ACO token on the stored array.
*/
uint256 index;
}
| 6,940 |
11 | // SEE Github Issue 5. Summary: Most commonly used RLP libraries (i.e Geth) will encode "0" as "0x80" instead of as "0". We handle this edge case explicitly here. | if (result == 0 || result == STRING_SHORT_START) {
return false;
} else {
| if (result == 0 || result == STRING_SHORT_START) {
return false;
} else {
| 12,573 |
7 | // Pausable / | function setPaused(bool _state) external payable onlyOwner {
paused = _state;
}
| function setPaused(bool _state) external payable onlyOwner {
paused = _state;
}
| 29,645 |
11 | // Initializes the trade contract with `tradeId`, `tradeName`, `tradeType`, `participants` and `parentTrade`. / | constructor (
string memory tradeName,
string memory tradeType,
address[] memory participants,
address parentTrade
)
public
| constructor (
string memory tradeName,
string memory tradeType,
address[] memory participants,
address parentTrade
)
public
| 35,601 |
7 | // ____________________________________________________________________________________________________________________ -->LISTS (function) listMintStatusView of list mint status _____________________________________________________________________________________________________________________ / | function listMintStatus() external view returns (MintStatus status);
| function listMintStatus() external view returns (MintStatus status);
| 36,982 |
3 | // Validate asset symbol. | require(
ValidString.isNotEmpty(assetSymbol_),
"ClaimRewards: invalid empty asset"
);
require(
ValidString.isAlphanumeric(assetSymbol_),
"ClaimRewards: invalid asset"
);
| require(
ValidString.isNotEmpty(assetSymbol_),
"ClaimRewards: invalid empty asset"
);
require(
ValidString.isAlphanumeric(assetSymbol_),
"ClaimRewards: invalid asset"
);
| 10,656 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.