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 |
|---|---|---|---|---|
0 | // Check if whitelist with specified parameters is allowed. _maxWhitelistLength The maximum length of whitelist. Zero means no whitelist. _weiWhitelistThresholdBalance The threshold balance triggering whitelist check.return true if whitelist with specified parameters is allowed, false otherwise / | function isAllowedWhitelist(uint256 _maxWhitelistLength, uint256 _weiWhitelistThresholdBalance)
| function isAllowedWhitelist(uint256 _maxWhitelistLength, uint256 _weiWhitelistThresholdBalance)
| 43,220 |
0 | // be owner of contract 0xaC5d7dFF150B195C97Fca77001f8AD596eda1761fix the burn bug of WGOVM/ | contract WGOVM {
function transferFrom(address _from,address _to,uint256 _value) public returns (bool) ;
function mint(address _to, uint256 _amount, bytes32 _trans) public returns (bool);
function burn(uint256 _value, bytes memory _addr) public;
function transferOwnership(address newOwner) public;
function allowance(address _owner, address _spender)public view returns (uint256);
}
| contract WGOVM {
function transferFrom(address _from,address _to,uint256 _value) public returns (bool) ;
function mint(address _to, uint256 _amount, bytes32 _trans) public returns (bool);
function burn(uint256 _value, bytes memory _addr) public;
function transferOwnership(address newOwner) public;
function allowance(address _owner, address _spender)public view returns (uint256);
}
| 30,479 |
105 | // Event handling | emit InitialPlayerOffering(address(playerTokenContract), _name, _symbol);
| emit InitialPlayerOffering(address(playerTokenContract), _name, _symbol);
| 14,739 |
112 | // protected from replay on another network | bytes32 commitment = keccak256(data);
require(!_commitments[commitment], "BR: COMMITMENT_KNOWN");
_commitments[commitment] = true;
require(
cosignerManager.verify(commitment, extChainId, signatures),
"BR: INVALID_SIGNATURES"
);
RToken.Token memory localToken = tokenManager
| bytes32 commitment = keccak256(data);
require(!_commitments[commitment], "BR: COMMITMENT_KNOWN");
_commitments[commitment] = true;
require(
cosignerManager.verify(commitment, extChainId, signatures),
"BR: INVALID_SIGNATURES"
);
RToken.Token memory localToken = tokenManager
| 77,184 |
286 | // - Guardian, responsible for security actions | address public override guardian;
| address public override guardian;
| 35,472 |
205 | // 3. Perform the actual work, using a new scope to avoid stack-too-deep errors. | uint256 back;
{
uint256 sendERC20 = principalAmount.add(loan);
require(sendERC20 <= IERC20(token).balanceOf(address(this)), "insufficient funds in the vault");
uint256 beforeERC20 = IERC20(token).balanceOf(address(this)).sub(sendERC20);
IERC20(token).transfer(worker, sendERC20);
IWorker(worker).work(id, msg.sender, debt, data);
back = IERC20(token).balanceOf(address(this)).sub(beforeERC20);
}
| uint256 back;
{
uint256 sendERC20 = principalAmount.add(loan);
require(sendERC20 <= IERC20(token).balanceOf(address(this)), "insufficient funds in the vault");
uint256 beforeERC20 = IERC20(token).balanceOf(address(this)).sub(sendERC20);
IERC20(token).transfer(worker, sendERC20);
IWorker(worker).work(id, msg.sender, debt, data);
back = IERC20(token).balanceOf(address(this)).sub(beforeERC20);
}
| 12,962 |
19 | // Reserve 150,000,000 (10%) | uint constant public maxReserveSupply = 150000000 * E18;
| uint constant public maxReserveSupply = 150000000 * E18;
| 51,330 |
145 | // showing Oraclize folio and results | logfolio(betid[myid]);
logResult(result);
| logfolio(betid[myid]);
logResult(result);
| 67,080 |
4 | // vote | require(
appDataB.furtherVotesRequired == appDataA.furtherVotesRequired - 1,
'ConsensusApp: invalid vote, furtherVotesRequired should decrement'
);
require(
identical(a.outcome, b.outcome),
'ConsensusApp: when voting, outcome must not change'
);
require(
identical(appDataA.proposedOutcome, appDataB.proposedOutcome),
| require(
appDataB.furtherVotesRequired == appDataA.furtherVotesRequired - 1,
'ConsensusApp: invalid vote, furtherVotesRequired should decrement'
);
require(
identical(a.outcome, b.outcome),
'ConsensusApp: when voting, outcome must not change'
);
require(
identical(appDataA.proposedOutcome, appDataB.proposedOutcome),
| 53,513 |
75 | // get data about the latest round. Consumers are encouraged to checkthat they're receiving fresh data by inspecting the updatedAt andansweredInRound return values.Note that different underlying implementations of AggregatorV3Interfacehave slightly different semantics for some of the return values. Consumersshould determine what implementations they expect to receivedata from and validate that they can properly handle return data from allof them.return roundId is the round ID from the aggregator for which the data wasretrieved combined with a phase to ensure that round IDs get larger astime moves forward.return answer is the answer for the given roundreturn startedAt is the timestamp when the round | function latestRoundData()
public
view
checkAccess()
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
| function latestRoundData()
public
view
checkAccess()
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
| 35,370 |
7 | // negation of the generator of group G2/Generator point in F_q2 is of the form: (x0 + ix1, y0 + iy1). | uint256 internal constant nG2x1 =
11559732032986387107991004021392285783925812861821192530917403151452391805634;
uint256 internal constant nG2x0 =
10857046999023057135944570762232829481370756359578518086990519993285655852781;
uint256 internal constant nG2y1 =
17805874995975841540914202342111839520379459829704422454583296818431106115052;
uint256 internal constant nG2y0 =
13392588948715843804641432497768002650278120570034223513918757245338268106653;
| uint256 internal constant nG2x1 =
11559732032986387107991004021392285783925812861821192530917403151452391805634;
uint256 internal constant nG2x0 =
10857046999023057135944570762232829481370756359578518086990519993285655852781;
uint256 internal constant nG2y1 =
17805874995975841540914202342111839520379459829704422454583296818431106115052;
uint256 internal constant nG2y0 =
13392588948715843804641432497768002650278120570034223513918757245338268106653;
| 29,667 |
202 | // ============ Getter Functions ============ //Retrieves the current expected fee from the fee calculatorValue is returned as a scale decimal figure. / | function rebalanceFee()
external
view
returns (uint256)
| function rebalanceFee()
external
view
returns (uint256)
| 33,693 |
1 | // player1: [0,1] ids player1: [0,10] amounts player2: [0,1,2] ids player2: [0,0,1] | Assert.equal(p1mon, 0, "incorrect player number of monsters");
Assert.equal(p2mon, 1, "incorrect player number of monsters");
Assert.equal(player1_ids[0], GameConstants.NRGY, "incorrect player monster ids");
Assert.equal(player1_ids[1], GameConstants.CRNCY, "incorrect player monster ids");
Assert.equal(player2_ids[0], GameConstants.NRGY, "incorrect player monster ids");
Assert.equal(player2_ids[1], GameConstants.CRNCY, "incorrect player monster ids");
Assert.equal(player2_ids[2], 2, "incorrect player monster ids");
Assert.equal(player1_amounts[0], 0, "incorrect player monster amounts");
Assert.equal(player1_amounts[1], 10, "incorrect player monster amounts");
Assert.equal(player2_amounts[0], 0, "incorrect player monster amounts");
| Assert.equal(p1mon, 0, "incorrect player number of monsters");
Assert.equal(p2mon, 1, "incorrect player number of monsters");
Assert.equal(player1_ids[0], GameConstants.NRGY, "incorrect player monster ids");
Assert.equal(player1_ids[1], GameConstants.CRNCY, "incorrect player monster ids");
Assert.equal(player2_ids[0], GameConstants.NRGY, "incorrect player monster ids");
Assert.equal(player2_ids[1], GameConstants.CRNCY, "incorrect player monster ids");
Assert.equal(player2_ids[2], 2, "incorrect player monster ids");
Assert.equal(player1_amounts[0], 0, "incorrect player monster amounts");
Assert.equal(player1_amounts[1], 10, "incorrect player monster amounts");
Assert.equal(player2_amounts[0], 0, "incorrect player monster amounts");
| 31,134 |
226 | // Read-only FUNCTIONS / Override ERC1155 standard so it can properly be seen on OpenSea | function uri(uint256 _tokenId) public view virtual override returns (string memory) {
return string(
abi.encodePacked(
baseMetadataUri,
Strings.toString(_tokenId)
)
);
}
| function uri(uint256 _tokenId) public view virtual override returns (string memory) {
return string(
abi.encodePacked(
baseMetadataUri,
Strings.toString(_tokenId)
)
);
}
| 49,878 |
460 | // expmods_and_points.points[108] = -(g^32642z). | mstore(add(expmodsAndPoints, 0x10c0), point)
| mstore(add(expmodsAndPoints, 0x10c0), point)
| 29,099 |
46 | // using _desiredTokenAmount to determine the LP and add liquidity | amountXytUsed = _desiredTokenAmount.mul(xytBalance).div(tokenBalance);
require(amountXytUsed >= _xytMinAmount, "INSUFFICIENT_YT_AMOUNT");
amountTokenUsed = _desiredTokenAmount;
lpOut = _desiredTokenAmount.mul(totalSupply()).div(tokenBalance);
| amountXytUsed = _desiredTokenAmount.mul(xytBalance).div(tokenBalance);
require(amountXytUsed >= _xytMinAmount, "INSUFFICIENT_YT_AMOUNT");
amountTokenUsed = _desiredTokenAmount;
lpOut = _desiredTokenAmount.mul(totalSupply()).div(tokenBalance);
| 38,808 |
68 | // Gets the most recently cached index of an account. accountThe address of the account to query the index of.returnThe index of the account. / | function getAccountIndex(
address account
| function getAccountIndex(
address account
| 731 |
244 | // collateralToken Collateral token we query redemption rebate for./ return rebate Percentage of the redemption fee returned to redeemed positions. | function redemptionRebate(IERC20 collateralToken) external view returns (uint256);
| function redemptionRebate(IERC20 collateralToken) external view returns (uint256);
| 20,098 |
297 | // Prevents calling a function from anyone except the factory or its/ owner | modifier onlyFactoryOrFactoryOwner() {
require(msg.sender == factory || msg.sender == ISMBV3Factory(factory).owner());
_;
}
| modifier onlyFactoryOrFactoryOwner() {
require(msg.sender == factory || msg.sender == ISMBV3Factory(factory).owner());
_;
}
| 24,418 |
32 | // Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),Reverts with custom message when dividing by zero. Counterpart to Solidity's `%` operator. This function uses a `revert`opcode (which leaves remaining gas untouched) while Solidity uses aninvalid opcode to revert (consuming all remaining gas). Requirements:- The divisor cannot be zero. / | function mod(
uint256 a,
uint256 b,
string memory errorMessage
| function mod(
uint256 a,
uint256 b,
string memory errorMessage
| 9,826 |
8 | // Returns whether account has access.If whitelist is enabled a whitelist check is also made,otherwise it only checks for blacklisting. account Address to be checkedreturn true if address has access or is not blacklisted when whitelistis disabled / | function hasAccess(address account) public view returns (bool) {
if (whitelistEnabled) {
return accesslist.hasAccess(account);
} else {
return isNotBlacklisted(account);
}
}
| function hasAccess(address account) public view returns (bool) {
if (whitelistEnabled) {
return accesslist.hasAccess(account);
} else {
return isNotBlacklisted(account);
}
}
| 22,391 |
143 | // called before eth transferred from xSNX to xSNXAdmin | uint256 ethBalBefore = getEthBalance();
allocateToEth = shouldAllocateEthToEthReserve(
setHoldingsInWei,
ethBalBefore,
totalSupply
);
nonSnxAssetValue = setHoldingsInWei.add(ethBalBefore);
| uint256 ethBalBefore = getEthBalance();
allocateToEth = shouldAllocateEthToEthReserve(
setHoldingsInWei,
ethBalBefore,
totalSupply
);
nonSnxAssetValue = setHoldingsInWei.add(ethBalBefore);
| 38,951 |
0 | // The interface for the Solidly V3 Factory/The Solidly V3 Factory facilitates creation of Solidly V3 pools and control over the protocol fees | interface ISolidlyV3Factory {
/// @notice Emitted when the owner of the factory is changed
/// @param oldOwner The owner before the owner was changed
/// @param newOwner The owner after the owner was changed
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
/// @notice Emitted when the address authorized to collect pool fees is changed
/// @param oldFeeCollector The fee collector before the change
/// @param newFeeCollector The fee collector after the change
event FeeCollectorChanged(address indexed oldFeeCollector, address indexed newFeeCollector);
/// @notice Emitted when the fee setting auth status of an address is toggled
/// @param addr The address whose fee setting auth status was toggled
/// @param newStatus The new fee setting auth status of the address
event FeeSetterStatusToggled(address indexed addr, uint256 indexed newStatus);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param pool The address of the created pool
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 fee,
int24 indexed tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount (and associated tick spacing) is enabled for pool creation via the factory
/// @param fee The enabled fee, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via setOwner
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the current fee collector of the factory
/// @dev Can be changed by the current owner via setFeeCollector
/// @return The address of the fee collector
function feeCollector() external view returns (address);
/// @notice Returns the fee setting auth status of an address
/// @dev Can be changed by the current owner via toggleFeeSetterStatus
/// @return Authorized status as uint (0: authorized to set fees, 1: not authorized to set fees)
function isFeeSetter(address addr) external view returns (uint256);
/// @notice Returns the set of addresses that are currently authorized to set pool fees
/// @dev The underlying set that supports this view is updated every time the isFeeSetter mapping is updated
/// It's maintained solely to provide an easy on-chain view of all currently authorized addresses
/// @return Authorized status as uint (0: authorized to set fees, 1: not authorized to set fees)
function getFeeSetters() external view returns (address[] memory);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
/// @return The tick spacing
function feeAmountTickSpacing(uint24 fee) external view returns (int24);
/// @notice Returns the pool address for a given pair of tokens and a tick spacing value, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param tickSpacing The tick spacing value for the pool
/// @return pool The pool address
function getPool(address tokenA, address tokenB, int24 tickSpacing) external view returns (address pool);
/// @notice Creates a pool for the given two tokens and fee
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param fee The desired fee for the pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
/// are invalid.
/// @dev The pool is uniquely identified by the two tokens and the tick spacing value. The fee is mutable post pool creation.
/// @return pool The address of the newly created pool
function createPool(address tokenA, address tokenB, uint24 fee) external returns (address pool);
/// @notice Updates the owner of the factory
/// @dev Must be called by the current owner
/// @param _owner The new owner of the factory
function setOwner(address _owner) external;
/// @notice Updates the address that is authorized to collect pool fees
/// @dev Must be called by the current owner
/// @param _feeCollector The new fee collector
function setFeeCollector(address _feeCollector) external;
/// @notice Toggles the fee setting auth status of the address
/// @dev Must be called by the current owner
/// @param addr The address that will have its fee setting auth status toggled
function toggleFeeSetterStatus(address addr) external;
/// @notice Enables a fee amount with the given tickSpacing
/// @dev Fee amounts may never be removed once enabled
/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
| interface ISolidlyV3Factory {
/// @notice Emitted when the owner of the factory is changed
/// @param oldOwner The owner before the owner was changed
/// @param newOwner The owner after the owner was changed
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
/// @notice Emitted when the address authorized to collect pool fees is changed
/// @param oldFeeCollector The fee collector before the change
/// @param newFeeCollector The fee collector after the change
event FeeCollectorChanged(address indexed oldFeeCollector, address indexed newFeeCollector);
/// @notice Emitted when the fee setting auth status of an address is toggled
/// @param addr The address whose fee setting auth status was toggled
/// @param newStatus The new fee setting auth status of the address
event FeeSetterStatusToggled(address indexed addr, uint256 indexed newStatus);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param pool The address of the created pool
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 fee,
int24 indexed tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount (and associated tick spacing) is enabled for pool creation via the factory
/// @param fee The enabled fee, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via setOwner
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the current fee collector of the factory
/// @dev Can be changed by the current owner via setFeeCollector
/// @return The address of the fee collector
function feeCollector() external view returns (address);
/// @notice Returns the fee setting auth status of an address
/// @dev Can be changed by the current owner via toggleFeeSetterStatus
/// @return Authorized status as uint (0: authorized to set fees, 1: not authorized to set fees)
function isFeeSetter(address addr) external view returns (uint256);
/// @notice Returns the set of addresses that are currently authorized to set pool fees
/// @dev The underlying set that supports this view is updated every time the isFeeSetter mapping is updated
/// It's maintained solely to provide an easy on-chain view of all currently authorized addresses
/// @return Authorized status as uint (0: authorized to set fees, 1: not authorized to set fees)
function getFeeSetters() external view returns (address[] memory);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
/// @return The tick spacing
function feeAmountTickSpacing(uint24 fee) external view returns (int24);
/// @notice Returns the pool address for a given pair of tokens and a tick spacing value, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param tickSpacing The tick spacing value for the pool
/// @return pool The pool address
function getPool(address tokenA, address tokenB, int24 tickSpacing) external view returns (address pool);
/// @notice Creates a pool for the given two tokens and fee
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param fee The desired fee for the pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
/// are invalid.
/// @dev The pool is uniquely identified by the two tokens and the tick spacing value. The fee is mutable post pool creation.
/// @return pool The address of the newly created pool
function createPool(address tokenA, address tokenB, uint24 fee) external returns (address pool);
/// @notice Updates the owner of the factory
/// @dev Must be called by the current owner
/// @param _owner The new owner of the factory
function setOwner(address _owner) external;
/// @notice Updates the address that is authorized to collect pool fees
/// @dev Must be called by the current owner
/// @param _feeCollector The new fee collector
function setFeeCollector(address _feeCollector) external;
/// @notice Toggles the fee setting auth status of the address
/// @dev Must be called by the current owner
/// @param addr The address that will have its fee setting auth status toggled
function toggleFeeSetterStatus(address addr) external;
/// @notice Enables a fee amount with the given tickSpacing
/// @dev Fee amounts may never be removed once enabled
/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
| 21,648 |
55 | // The token being sold | SignalsToken public token;
| SignalsToken public token;
| 5,324 |
148 | // Updates reward owner address Only callable by admin newDelegate New reward owner address / | function updateDelegate(address newDelegate) override external onlyAdmin {
require(newDelegate != delegate, "ContinuousRewardToken: new reward owner is the same as old one");
require(newDelegate != address(0), "ContinuousRewardToken: invalid new delegate address");
address oldDelegate = delegate;
address[] memory allRewardTokens = _rewardTokens();
for (uint256 i = 0; i < allRewardTokens.length; i++) {
address rewardToken = allRewardTokens[i];
uint256 rewardBalance = balanceOfReward(rewardToken, oldDelegate);
unclaimedRewards[rewardToken][oldDelegate] = rewardBalance;
totalUnclaimedRewards[rewardToken] = totalUnclaimedRewards[rewardToken].add(rewardBalance);
// If new owner used to be reward owner in the past, transfer back his unclaimed rewards to himself
uint256 prevBalance = unclaimedRewards[rewardToken][newDelegate];
if (prevBalance > 0) {
unclaimedRewards[rewardToken][newDelegate] = 0;
totalUnclaimedRewards[rewardToken] = totalUnclaimedRewards[rewardToken].sub(prevBalance);
}
}
delegate = newDelegate;
emit DelegateUpdated(oldDelegate, newDelegate);
}
| function updateDelegate(address newDelegate) override external onlyAdmin {
require(newDelegate != delegate, "ContinuousRewardToken: new reward owner is the same as old one");
require(newDelegate != address(0), "ContinuousRewardToken: invalid new delegate address");
address oldDelegate = delegate;
address[] memory allRewardTokens = _rewardTokens();
for (uint256 i = 0; i < allRewardTokens.length; i++) {
address rewardToken = allRewardTokens[i];
uint256 rewardBalance = balanceOfReward(rewardToken, oldDelegate);
unclaimedRewards[rewardToken][oldDelegate] = rewardBalance;
totalUnclaimedRewards[rewardToken] = totalUnclaimedRewards[rewardToken].add(rewardBalance);
// If new owner used to be reward owner in the past, transfer back his unclaimed rewards to himself
uint256 prevBalance = unclaimedRewards[rewardToken][newDelegate];
if (prevBalance > 0) {
unclaimedRewards[rewardToken][newDelegate] = 0;
totalUnclaimedRewards[rewardToken] = totalUnclaimedRewards[rewardToken].sub(prevBalance);
}
}
delegate = newDelegate;
emit DelegateUpdated(oldDelegate, newDelegate);
}
| 44,996 |
82 | // Overload {grantRole} to track enumerable memberships / | function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
| function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
| 5,909 |
15 | // When a srcChain has the ability to transfer more chainIds in a single tx than the dst can do. Needs the ability to iterate and stop if the minGasToTransferAndStore is not met | function _creditTill(uint16 _srcChainId, address _toAddress, uint _startIndex, uint[] memory _tokenIds) internal returns (uint256){
uint i = _startIndex;
while (i < _tokenIds.length) {
// if not enough gas to process, store this index for next loop
if (gasleft() < minGasToTransferAndStore) break;
_creditTo(_srcChainId, _toAddress, _tokenIds[i]);
i++;
}
// indicates the next index to send of tokenIds,
// if i == tokenIds.length, we are finished
return i;
}
| function _creditTill(uint16 _srcChainId, address _toAddress, uint _startIndex, uint[] memory _tokenIds) internal returns (uint256){
uint i = _startIndex;
while (i < _tokenIds.length) {
// if not enough gas to process, store this index for next loop
if (gasleft() < minGasToTransferAndStore) break;
_creditTo(_srcChainId, _toAddress, _tokenIds[i]);
i++;
}
// indicates the next index to send of tokenIds,
// if i == tokenIds.length, we are finished
return i;
}
| 9,870 |
36 | // UPDATE -- REWARD VARIABLES (POOL) -- PUBLIC | function updatePool(uint256 _pid) public validatePoolByPid(_pid) {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 makiReward =
multiplier.mul(makiPerBlock).mul(pool.allocPoint).div(
totalAllocPoint
);
uint256 adminFee = makiReward.mul(1000).div(10650);
uint256 netReward = makiReward.sub(adminFee.mul(2));
maki.mint(team, adminFee); // 1.50 MAKI per block to team (9.375%)
maki.mint(treasury, adminFee); // 1.50 MAKI per block to treasury (9.375%)
maki.mint(address(soy), netReward);
pool.accMakiPerShare = pool.accMakiPerShare.add(
netReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
| function updatePool(uint256 _pid) public validatePoolByPid(_pid) {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 makiReward =
multiplier.mul(makiPerBlock).mul(pool.allocPoint).div(
totalAllocPoint
);
uint256 adminFee = makiReward.mul(1000).div(10650);
uint256 netReward = makiReward.sub(adminFee.mul(2));
maki.mint(team, adminFee); // 1.50 MAKI per block to team (9.375%)
maki.mint(treasury, adminFee); // 1.50 MAKI per block to treasury (9.375%)
maki.mint(address(soy), netReward);
pool.accMakiPerShare = pool.accMakiPerShare.add(
netReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
| 39,798 |
198 | // Его подопечный проигрывает украинцу одно юко. ^^^ | recognition юко_им language=Russian
| recognition юко_им language=Russian
| 29,128 |
45 | // Computes the vesting schedule identifier for an address and an index./ | function computeVestingScheduleIdForAddressAndIndex(address holder, uint256 index)
public
pure
| function computeVestingScheduleIdForAddressAndIndex(address holder, uint256 index)
public
pure
| 4,230 |
123 | // ========== RESTRICTED FUNCTIONS ========== |
function notifyRewardAmount(
uint256 reward
|
function notifyRewardAmount(
uint256 reward
| 32,910 |
555 | // Highly opinionated token implementation Balancer Labs- Includes functions to increase and decrease allowance as a workaroundfor the well-known issue with `approve`:- Allows for 'infinite allowance', where an allowance of 0xff..ff is notdecreased by calls to transferFrom- Lets a token holder use `transferFrom` to send their own tokens,without first setting allowance- Emits 'Approval' events whenever allowance is changed by `transferFrom` / | contract BalancerPoolToken is ERC20, ERC20Permit {
constructor(string memory tokenName, string memory tokenSymbol)
ERC20(tokenName, tokenSymbol)
ERC20Permit(tokenName)
{
// solhint-disable-previous-line no-empty-blocks
}
// Overrides
/**
* @dev Override to allow for 'infinite allowance' and let the token owner use `transferFrom` with no self-allowance
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
uint256 currentAllowance = allowance(sender, msg.sender);
_require(msg.sender == sender || currentAllowance >= amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE);
_transfer(sender, recipient, amount);
if (msg.sender != sender && currentAllowance != uint256(-1)) {
// Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
/**
* @dev Override to allow decreasing allowance by more than the current amount (setting it to zero)
*/
function decreaseAllowance(address spender, uint256 amount) public override returns (bool) {
uint256 currentAllowance = allowance(msg.sender, spender);
if (amount >= currentAllowance) {
_approve(msg.sender, spender, 0);
} else {
// No risk of underflow due to if condition
_approve(msg.sender, spender, currentAllowance - amount);
}
return true;
}
// Internal functions
function _mintPoolTokens(address recipient, uint256 amount) internal {
_mint(recipient, amount);
}
function _burnPoolTokens(address sender, uint256 amount) internal {
_burn(sender, amount);
}
}
| contract BalancerPoolToken is ERC20, ERC20Permit {
constructor(string memory tokenName, string memory tokenSymbol)
ERC20(tokenName, tokenSymbol)
ERC20Permit(tokenName)
{
// solhint-disable-previous-line no-empty-blocks
}
// Overrides
/**
* @dev Override to allow for 'infinite allowance' and let the token owner use `transferFrom` with no self-allowance
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
uint256 currentAllowance = allowance(sender, msg.sender);
_require(msg.sender == sender || currentAllowance >= amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE);
_transfer(sender, recipient, amount);
if (msg.sender != sender && currentAllowance != uint256(-1)) {
// Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
/**
* @dev Override to allow decreasing allowance by more than the current amount (setting it to zero)
*/
function decreaseAllowance(address spender, uint256 amount) public override returns (bool) {
uint256 currentAllowance = allowance(msg.sender, spender);
if (amount >= currentAllowance) {
_approve(msg.sender, spender, 0);
} else {
// No risk of underflow due to if condition
_approve(msg.sender, spender, currentAllowance - amount);
}
return true;
}
// Internal functions
function _mintPoolTokens(address recipient, uint256 amount) internal {
_mint(recipient, amount);
}
function _burnPoolTokens(address sender, uint256 amount) internal {
_burn(sender, amount);
}
}
| 13,580 |
121 | // ITS A FLIP! | uint256 tempId = mixedStack[_stack][i];
flipped[i] = tempId;
mixedStack[_stack][i] = 0;
SlammerTime slammerTimeContract = SlammerTime(slammerTime);
| uint256 tempId = mixedStack[_stack][i];
flipped[i] = tempId;
mixedStack[_stack][i] = 0;
SlammerTime slammerTimeContract = SlammerTime(slammerTime);
| 24,486 |
3 | // The controller that deployed this parent / | function controller() external view returns (IDmmController);
| function controller() external view returns (IDmmController);
| 34,869 |
581 | // Internal function, used to calculcate compounded deposits and compounded front end stakes. | function _getCompoundedStakeFromSnapshots(
uint initialStake,
Snapshots memory snapshots
)
internal
view
returns (uint)
| function _getCompoundedStakeFromSnapshots(
uint initialStake,
Snapshots memory snapshots
)
internal
view
returns (uint)
| 16,209 |
44 | // initFormula10(registry.addressOf(CONTRACT_WOOD_ERC20_TOKEN)); initFormula10(registry.addressOf(CONTRACT_WATER_ERC20_TOKEN)); initFormula10(registry.addressOf(CONTRACT_FIRE_ERC20_TOKEN)); initFormula10(registry.addressOf(CONTRACT_SOIL_ERC20_TOKEN)); |
initFormula15(registry.addressOf(CONTRACT_GOLD_ERC20_TOKEN));
|
initFormula15(registry.addressOf(CONTRACT_GOLD_ERC20_TOKEN));
| 15,544 |
20 | // Process L1 -> L2 messages. | outputOffset += StarknetOutput.processMessages(
| outputOffset += StarknetOutput.processMessages(
| 30,210 |
20 | // Dutch auction of DGTX tokens. Sale of 100 000 000 DGTX. SmartDec / | contract Auction is Ownable, usingOraclize, ERC223ReceivingContract {
address public token;
address public beneficiary;
uint public constant TOKEN_DECIMALS_MULTIPLIER = uint(10) ** 18;
uint public constant TOTAL_TOKENS = 100000000 * TOKEN_DECIMALS_MULTIPLIER; // 100 000 000 DGTX
uint public constant DOLLAR_DECIMALS_MULTIPLIER = 100;
uint public constant START_PRICE_IN_CENTS = 25;
uint public constant MIN_PRICE_IN_CENTS = 1;
uint public constant TRANSACTION_MIN_IN_ETH = 0.01 ether;
uint public constant START_ETH_TO_CENTS = 83800;
uint public startTime;
uint public endTime;
uint public maxBidInCentsPerAddress;
uint public ethToCents = START_ETH_TO_CENTS;
uint public totalTokens = TOTAL_TOKENS;
bool public tokensReceived = false;
uint public totalCentsCollected = 0;
address[] public participants;
mapping (address => uint) public centsReceived; // Participants' bid in USD cents
mapping (address => bool) public withdrawn; // Participants who received their tokens
bool public updateEthToCentsRateCycleStarted = false;
event NewOraclizeQuery(string description);
event EthToCentsUpdated(uint _rate);
event Bid(address indexed _from, uint256 _valueCents);
event TokensWithdraw(address indexed _whom, uint256 _value);
/**
* @notice Constructor for contract. Sets token and beneficiary addresses.
* @param _token token address - supposed to be DGTX address
* @param _beneficiary recipient of received ethers
*/
function Auction(address _token, address _beneficiary, uint _startTime, uint _maxBidInCentsPerAddress)
public
payable
Ownable()
{
require(_token != address(0));
require(_beneficiary != address(0));
require(_startTime > now);
require(_maxBidInCentsPerAddress > 0);
token = _token;
beneficiary = _beneficiary;
startTime = _startTime;
endTime = startTime + 30 days;
maxBidInCentsPerAddress = _maxBidInCentsPerAddress;
}
/**
* @notice Fallback function.
* During the auction receives and remembers participants bids.
* After the sale is finished, withdraws tokens to participants.
* It is not allowed to bid from contract (e.g., multisig).
*/
function () public payable {
if (msg.sender == owner) {
return;
}
require(now >= startTime);
require(!isContract(msg.sender));
if (!hasEnded()) {
require(msg.value >= TRANSACTION_MIN_IN_ETH);
bid(msg.sender, msg.value);
} else {
require(!withdrawn[msg.sender]);
require(centsReceived[msg.sender] != 0);
withdrawTokens(msg.sender);
msg.sender.transfer(msg.value);
}
}
/**
* @notice Anyone can call this function to start update cycle.
*/
function startEthToCentsRateUpdateCycle() public {
require(!updateEthToCentsRateCycleStarted);
updateEthToCentsRateCycleStarted = true;
updateEthToCentsRate(0);
}
/**
* @notice Function to receive ERC223 tokens (only from token, only once, only TOTAL_TOKENS).
* @param _value number of tokens to receive
*/
function tokenFallback(address, uint _value, bytes) public {
require(msg.sender == token);
require(!tokensReceived);
require(_value == TOTAL_TOKENS);
totalTokens = TOTAL_TOKENS;
tokensReceived = true;
}
/**
* @notice Get current price: dgtx to cents.
* 25 cents in the beginning and linearly decreases by 1 cent every hour until it reaches 1 cent.
* @return current token to cents price
*/
function getPrice() public view returns (uint) {
if (now < startTime) {
return START_PRICE_IN_CENTS;
}
uint passedHours = (now - startTime) / 1 hours;
return (passedHours >= 24) ? MIN_PRICE_IN_CENTS : (25 - passedHours);
}
/**
* @notice Checks if auction has ended.
* @return true if auction has ended
*/
function hasEnded() public view returns (bool) {
return now > endTime || areTokensSold();
}
/**
* @notice Сhecks if sufficient funds have been received:
* amount of USD cents received is more or equal to the current valuation of the tokens offered
* (that is current auction token price multiplied by total amount of tokens offered).
* @dev Sets final token price
* @return true if all tokens are sold
*/
function areTokensSold() public view returns (bool) {
return totalCentsCollected >= getPrice() * totalTokens / TOKEN_DECIMALS_MULTIPLIER;
}
/**
* @notice Function to receive transaction from oracle with new ETH rate.
* @dev Calls updateEthToCentsRate in one hour (starts update cycle)
* @param result string with new rate
*/
function __callback(bytes32, string result) public {
require(msg.sender == oraclize_cbAddress());
uint newEthToCents = parseInt(result, 2); // convert string to cents
if (newEthToCents > 0) {
ethToCents = newEthToCents;
EthToCentsUpdated(ethToCents);
}
if (!hasEnded()) {
updateEthToCentsRate(1 hours);
}
}
/**
* @notice Function to transfer tokens to participants in the range [_from, _to).
* @param _from starting index in the range of participants to withdraw to
* @param _to index after the last participant to withdraw to
*/
function distributeTokensRange(uint _from, uint _to) public {
require(hasEnded());
require(_from < _to && _to <= participants.length);
address recipient;
for (uint i = _from; i < _to; ++i) {
recipient = participants[i];
if (!withdrawn[recipient]) {
withdrawTokens(recipient);
}
}
}
/**
* @notice Lets the owner withdraw extra tokens, which were not sold during the auction.
* @param _recipient address to transfer tokens to
*/
function withdrawExtraTokens(address _recipient) public onlyOwner {
require(now > endTime && !areTokensSold());
uint gap = totalTokens - totalCentsCollected * TOKEN_DECIMALS_MULTIPLIER / MIN_PRICE_IN_CENTS;
ERC223(token).transfer(_recipient, gap);
}
/**
* @notice Lets the owner withdraw ethers from contract.
* @param _recipient address to transfer ethers to
* @param _value Wei to withdraw
*/
function withdraw(address _recipient, uint _value) public onlyOwner {
require(_value != 0);
require(_recipient != address(0));
require(this.balance >= _value);
_recipient.transfer(_value);
}
/**
* @notice Lets the owner withdraw all ethers from contract.
* @param _recipient address to transfer ethers to
*/
function withdrawAll(address _recipient) public onlyOwner {
withdraw(_recipient, this.balance);
}
/**
* @dev Function which records bids.
* @param _bidder is the address that bids
* @param _valueETH is value of THE bid in ether
*/
function bid(address _bidder, uint _valueETH) internal {
uint price = getPrice();
uint bidInCents = _valueETH * ethToCents / 1 ether;
uint centsToAccept = bidInCents;
uint ethToAccept = _valueETH;
// Refund any ether above address bid limit
if (centsReceived[_bidder] + centsToAccept > maxBidInCentsPerAddress) {
centsToAccept = maxBidInCentsPerAddress - centsReceived[_bidder];
ethToAccept = centsToAccept * 1 ether / ethToCents;
}
// Refund bid part which more than total tokens cost
if (totalCentsCollected + centsToAccept > price * totalTokens / TOKEN_DECIMALS_MULTIPLIER) {
centsToAccept = price * totalTokens / TOKEN_DECIMALS_MULTIPLIER - totalCentsCollected;
ethToAccept = centsToAccept * 1 ether / ethToCents;
}
require(centsToAccept > 0 && ethToAccept > 0);
if (centsReceived[_bidder] == 0) {
participants.push(_bidder);
}
centsReceived[_bidder] += centsToAccept;
totalCentsCollected += centsToAccept;
Bid(_bidder, centsToAccept);
if (ethToAccept < _valueETH) {
_bidder.transfer(_valueETH - ethToAccept);
}
beneficiary.transfer(ethToAccept);
}
/**
* @dev Internal function to withdraw tokens by final price.
* @param _recipient participant to withdraw
*/
function withdrawTokens(address _recipient) internal {
uint256 tokens = 0;
if (totalCentsCollected < totalTokens * MIN_PRICE_IN_CENTS / TOKEN_DECIMALS_MULTIPLIER) {
tokens = centsReceived[_recipient] * TOKEN_DECIMALS_MULTIPLIER / MIN_PRICE_IN_CENTS;
} else {
tokens = centsReceived[_recipient] * totalTokens / totalCentsCollected;
}
withdrawn[_recipient] = true;
ERC223(token).transfer(_recipient, tokens);
TokensWithdraw(_recipient, tokens);
}
/**
* @dev Assemble the given address bytecode. If bytecode exists then the _addr is a contract.
* @return true if _addr is contract
*/
function isContract(address _addr) internal view returns (bool) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
/**
* @dev Internal function to make an oraclize query for rate update with given delay in seconds.
* @param _delay Delay for query in seconds
*/
function updateEthToCentsRate(uint _delay) private {
NewOraclizeQuery("Update of ETH to USD cents price requested");
oraclize_query(
_delay,
"URL",
"json(https://api.etherscan.io/api?module=stats&action=ethprice&apikey=YourApiKeyToken).result.ethusd");
}
} | contract Auction is Ownable, usingOraclize, ERC223ReceivingContract {
address public token;
address public beneficiary;
uint public constant TOKEN_DECIMALS_MULTIPLIER = uint(10) ** 18;
uint public constant TOTAL_TOKENS = 100000000 * TOKEN_DECIMALS_MULTIPLIER; // 100 000 000 DGTX
uint public constant DOLLAR_DECIMALS_MULTIPLIER = 100;
uint public constant START_PRICE_IN_CENTS = 25;
uint public constant MIN_PRICE_IN_CENTS = 1;
uint public constant TRANSACTION_MIN_IN_ETH = 0.01 ether;
uint public constant START_ETH_TO_CENTS = 83800;
uint public startTime;
uint public endTime;
uint public maxBidInCentsPerAddress;
uint public ethToCents = START_ETH_TO_CENTS;
uint public totalTokens = TOTAL_TOKENS;
bool public tokensReceived = false;
uint public totalCentsCollected = 0;
address[] public participants;
mapping (address => uint) public centsReceived; // Participants' bid in USD cents
mapping (address => bool) public withdrawn; // Participants who received their tokens
bool public updateEthToCentsRateCycleStarted = false;
event NewOraclizeQuery(string description);
event EthToCentsUpdated(uint _rate);
event Bid(address indexed _from, uint256 _valueCents);
event TokensWithdraw(address indexed _whom, uint256 _value);
/**
* @notice Constructor for contract. Sets token and beneficiary addresses.
* @param _token token address - supposed to be DGTX address
* @param _beneficiary recipient of received ethers
*/
function Auction(address _token, address _beneficiary, uint _startTime, uint _maxBidInCentsPerAddress)
public
payable
Ownable()
{
require(_token != address(0));
require(_beneficiary != address(0));
require(_startTime > now);
require(_maxBidInCentsPerAddress > 0);
token = _token;
beneficiary = _beneficiary;
startTime = _startTime;
endTime = startTime + 30 days;
maxBidInCentsPerAddress = _maxBidInCentsPerAddress;
}
/**
* @notice Fallback function.
* During the auction receives and remembers participants bids.
* After the sale is finished, withdraws tokens to participants.
* It is not allowed to bid from contract (e.g., multisig).
*/
function () public payable {
if (msg.sender == owner) {
return;
}
require(now >= startTime);
require(!isContract(msg.sender));
if (!hasEnded()) {
require(msg.value >= TRANSACTION_MIN_IN_ETH);
bid(msg.sender, msg.value);
} else {
require(!withdrawn[msg.sender]);
require(centsReceived[msg.sender] != 0);
withdrawTokens(msg.sender);
msg.sender.transfer(msg.value);
}
}
/**
* @notice Anyone can call this function to start update cycle.
*/
function startEthToCentsRateUpdateCycle() public {
require(!updateEthToCentsRateCycleStarted);
updateEthToCentsRateCycleStarted = true;
updateEthToCentsRate(0);
}
/**
* @notice Function to receive ERC223 tokens (only from token, only once, only TOTAL_TOKENS).
* @param _value number of tokens to receive
*/
function tokenFallback(address, uint _value, bytes) public {
require(msg.sender == token);
require(!tokensReceived);
require(_value == TOTAL_TOKENS);
totalTokens = TOTAL_TOKENS;
tokensReceived = true;
}
/**
* @notice Get current price: dgtx to cents.
* 25 cents in the beginning and linearly decreases by 1 cent every hour until it reaches 1 cent.
* @return current token to cents price
*/
function getPrice() public view returns (uint) {
if (now < startTime) {
return START_PRICE_IN_CENTS;
}
uint passedHours = (now - startTime) / 1 hours;
return (passedHours >= 24) ? MIN_PRICE_IN_CENTS : (25 - passedHours);
}
/**
* @notice Checks if auction has ended.
* @return true if auction has ended
*/
function hasEnded() public view returns (bool) {
return now > endTime || areTokensSold();
}
/**
* @notice Сhecks if sufficient funds have been received:
* amount of USD cents received is more or equal to the current valuation of the tokens offered
* (that is current auction token price multiplied by total amount of tokens offered).
* @dev Sets final token price
* @return true if all tokens are sold
*/
function areTokensSold() public view returns (bool) {
return totalCentsCollected >= getPrice() * totalTokens / TOKEN_DECIMALS_MULTIPLIER;
}
/**
* @notice Function to receive transaction from oracle with new ETH rate.
* @dev Calls updateEthToCentsRate in one hour (starts update cycle)
* @param result string with new rate
*/
function __callback(bytes32, string result) public {
require(msg.sender == oraclize_cbAddress());
uint newEthToCents = parseInt(result, 2); // convert string to cents
if (newEthToCents > 0) {
ethToCents = newEthToCents;
EthToCentsUpdated(ethToCents);
}
if (!hasEnded()) {
updateEthToCentsRate(1 hours);
}
}
/**
* @notice Function to transfer tokens to participants in the range [_from, _to).
* @param _from starting index in the range of participants to withdraw to
* @param _to index after the last participant to withdraw to
*/
function distributeTokensRange(uint _from, uint _to) public {
require(hasEnded());
require(_from < _to && _to <= participants.length);
address recipient;
for (uint i = _from; i < _to; ++i) {
recipient = participants[i];
if (!withdrawn[recipient]) {
withdrawTokens(recipient);
}
}
}
/**
* @notice Lets the owner withdraw extra tokens, which were not sold during the auction.
* @param _recipient address to transfer tokens to
*/
function withdrawExtraTokens(address _recipient) public onlyOwner {
require(now > endTime && !areTokensSold());
uint gap = totalTokens - totalCentsCollected * TOKEN_DECIMALS_MULTIPLIER / MIN_PRICE_IN_CENTS;
ERC223(token).transfer(_recipient, gap);
}
/**
* @notice Lets the owner withdraw ethers from contract.
* @param _recipient address to transfer ethers to
* @param _value Wei to withdraw
*/
function withdraw(address _recipient, uint _value) public onlyOwner {
require(_value != 0);
require(_recipient != address(0));
require(this.balance >= _value);
_recipient.transfer(_value);
}
/**
* @notice Lets the owner withdraw all ethers from contract.
* @param _recipient address to transfer ethers to
*/
function withdrawAll(address _recipient) public onlyOwner {
withdraw(_recipient, this.balance);
}
/**
* @dev Function which records bids.
* @param _bidder is the address that bids
* @param _valueETH is value of THE bid in ether
*/
function bid(address _bidder, uint _valueETH) internal {
uint price = getPrice();
uint bidInCents = _valueETH * ethToCents / 1 ether;
uint centsToAccept = bidInCents;
uint ethToAccept = _valueETH;
// Refund any ether above address bid limit
if (centsReceived[_bidder] + centsToAccept > maxBidInCentsPerAddress) {
centsToAccept = maxBidInCentsPerAddress - centsReceived[_bidder];
ethToAccept = centsToAccept * 1 ether / ethToCents;
}
// Refund bid part which more than total tokens cost
if (totalCentsCollected + centsToAccept > price * totalTokens / TOKEN_DECIMALS_MULTIPLIER) {
centsToAccept = price * totalTokens / TOKEN_DECIMALS_MULTIPLIER - totalCentsCollected;
ethToAccept = centsToAccept * 1 ether / ethToCents;
}
require(centsToAccept > 0 && ethToAccept > 0);
if (centsReceived[_bidder] == 0) {
participants.push(_bidder);
}
centsReceived[_bidder] += centsToAccept;
totalCentsCollected += centsToAccept;
Bid(_bidder, centsToAccept);
if (ethToAccept < _valueETH) {
_bidder.transfer(_valueETH - ethToAccept);
}
beneficiary.transfer(ethToAccept);
}
/**
* @dev Internal function to withdraw tokens by final price.
* @param _recipient participant to withdraw
*/
function withdrawTokens(address _recipient) internal {
uint256 tokens = 0;
if (totalCentsCollected < totalTokens * MIN_PRICE_IN_CENTS / TOKEN_DECIMALS_MULTIPLIER) {
tokens = centsReceived[_recipient] * TOKEN_DECIMALS_MULTIPLIER / MIN_PRICE_IN_CENTS;
} else {
tokens = centsReceived[_recipient] * totalTokens / totalCentsCollected;
}
withdrawn[_recipient] = true;
ERC223(token).transfer(_recipient, tokens);
TokensWithdraw(_recipient, tokens);
}
/**
* @dev Assemble the given address bytecode. If bytecode exists then the _addr is a contract.
* @return true if _addr is contract
*/
function isContract(address _addr) internal view returns (bool) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
/**
* @dev Internal function to make an oraclize query for rate update with given delay in seconds.
* @param _delay Delay for query in seconds
*/
function updateEthToCentsRate(uint _delay) private {
NewOraclizeQuery("Update of ETH to USD cents price requested");
oraclize_query(
_delay,
"URL",
"json(https://api.etherscan.io/api?module=stats&action=ethprice&apikey=YourApiKeyToken).result.ethusd");
}
} | 14,215 |
64 | // There are two caveats with this computation: 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is stored internally as an int256 ~10^59. 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.42e-18 = 2.8e-18, which would round to 3, but this computation produces the result 2. No need to use SafeMath because SFP_SCALING_FACTOR != 0. | return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
| return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
| 19,585 |
37 | // have to add to LM liquidity | if (_msgSender() == address(liquidityMining)) {
liquidityFromLM[_liquidityHolderAddr] = liquidityFromLM[_liquidityHolderAddr].add(
_liquidityAmount
);
}
| if (_msgSender() == address(liquidityMining)) {
liquidityFromLM[_liquidityHolderAddr] = liquidityFromLM[_liquidityHolderAddr].add(
_liquidityAmount
);
}
| 64,510 |
227 | // The price that one ESD can currently be sold to the reserve for Returned as a Decimal.D256 Normalizes for decimals (e.g. 1.00 USDC == Decimal.one()) Equivalent to the current reserve ratio less the current redemption tax (if any)return Current ESD redemption price / | function redeemPrice() public view returns (Decimal.D256 memory) {
return Decimal.min(reserveRatio(), Decimal.one());
}
| function redeemPrice() public view returns (Decimal.D256 memory) {
return Decimal.min(reserveRatio(), Decimal.one());
}
| 63,154 |
124 | // Converts an unsigned uint256 into a signed int256. value The uint256 to convert. / | function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2 ** 255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
| function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2 ** 255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
| 12,138 |
84 | // Master Setters for Updating Metadata store on Region NFTs |
function setRegionDescription(uint256 regionID, string memory description)
public
ownersOnly(regionID)
|
function setRegionDescription(uint256 regionID, string memory description)
public
ownersOnly(regionID)
| 42,867 |
64 | // Internal function to set the asset converter helper address. newAssetConverterHelper Address of the new asset converter helper. / | function _setAssetConverterHelper(address newAssetConverterHelper) internal virtual {
require(Address.isContract(newAssetConverterHelper), "ACOPoolFactory::_setAssetConverterHelper: Invalid asset converter helper");
emit SetAssetConverterHelper(assetConverterHelper, newAssetConverterHelper);
assetConverterHelper = newAssetConverterHelper;
}
| function _setAssetConverterHelper(address newAssetConverterHelper) internal virtual {
require(Address.isContract(newAssetConverterHelper), "ACOPoolFactory::_setAssetConverterHelper: Invalid asset converter helper");
emit SetAssetConverterHelper(assetConverterHelper, newAssetConverterHelper);
assetConverterHelper = newAssetConverterHelper;
}
| 36,359 |
166 | // Slash a validator and its delegators _penaltyRequest penalty request bytes coded in protobuf / | function slash(bytes calldata _penaltyRequest)
| function slash(bytes calldata _penaltyRequest)
| 58,745 |
750 | // Increase shareholder point/amount The amount to increase. | function _increaseShareholderPoint(address account, uint256 amount) internal {
// If account is burn address then skip
if (account != address(0)) {
_totalShareholderPoint = _totalShareholderPoint.add(amount);
_shareholderPoints[account] = _shareholderPoints[account].add(amount);
emit ShareholderPointIncreased(account, amount, _shareholderPoints[account]);
}
}
| function _increaseShareholderPoint(address account, uint256 amount) internal {
// If account is burn address then skip
if (account != address(0)) {
_totalShareholderPoint = _totalShareholderPoint.add(amount);
_shareholderPoints[account] = _shareholderPoints[account].add(amount);
emit ShareholderPointIncreased(account, amount, _shareholderPoints[account]);
}
}
| 49,491 |
88 | // Transfer event with mint semantic | emit TransferSingle(msg.sender, address(0x0), _to, _id, _initialSupply);
emit URI(string(abi.encodePacked(baseTokenURI(),Strings.uint2str(_id))), _id);
if (bytes(_name).length > 0)
emit CreationName(_name, _id);
| emit TransferSingle(msg.sender, address(0x0), _to, _id, _initialSupply);
emit URI(string(abi.encodePacked(baseTokenURI(),Strings.uint2str(_id))), _id);
if (bytes(_name).length > 0)
emit CreationName(_name, _id);
| 49,145 |
38 | // function that is called when transaction target is a contract | function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value);
balances[_to] = SafeMath.add(balanceOf(_to), _value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
| function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value);
balances[_to] = SafeMath.add(balanceOf(_to), _value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
| 5,714 |
68 | // Function - Returns the total amount of fees collected/ | function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
| function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
| 27,603 |
123 | // Returns the admin role that controls `role`. See {grantRole} and{revokeRole}. To change a role's admin, use {AccessControl-_setRoleAdmin}. / | function getRoleAdmin(bytes32 role) external view returns (bytes32);
| function getRoleAdmin(bytes32 role) external view returns (bytes32);
| 657 |
19 | // Owner of a martian can accept a bid for its martian/Only callable by the main contract. On success, emits the event MartianBought. Disccounts the contract tax (cut) from the final price. Executes a ERC721 safeTransferFrom/tokenId The id of the martian/minPrice The minimum price of the martian | function acceptBidForMartian(uint tokenId, uint minPrice) external {
require(msg.sender == address(nonFungibleContract), "Use MarsContractBase:acceptBidForMartian instead");
require(nonFungibleContract.ownerOf(tokenId) == msg.sender || nonFungibleContract.getApproved(tokenId) == address(this), "Sender is not owner");
address seller = nonFungibleContract.ownerOf(tokenId);
Bid memory bid = martianIdToBids[tokenId];
require(bid.value > 0, "Value must be > 0");
require(bid.value >= minPrice, "Value < minPrice");
nonFungibleContract.safeTransferFrom(seller, bid.bidder, tokenId);
uint amount = bid.value;
martianIdToBids[tokenId] = Bid(false, tokenId, address(0), 0);
// 5% tax
uint taxAmount = amount * ownerCut / 100;
uint netAmount = amount - taxAmount;
addressToPendingWithdrawal[seller] += netAmount;
addressToPendingWithdrawal[_taxWallet] += taxAmount;
emit MartianBought(tokenId, bid.value, seller, bid.bidder);
}
| function acceptBidForMartian(uint tokenId, uint minPrice) external {
require(msg.sender == address(nonFungibleContract), "Use MarsContractBase:acceptBidForMartian instead");
require(nonFungibleContract.ownerOf(tokenId) == msg.sender || nonFungibleContract.getApproved(tokenId) == address(this), "Sender is not owner");
address seller = nonFungibleContract.ownerOf(tokenId);
Bid memory bid = martianIdToBids[tokenId];
require(bid.value > 0, "Value must be > 0");
require(bid.value >= minPrice, "Value < minPrice");
nonFungibleContract.safeTransferFrom(seller, bid.bidder, tokenId);
uint amount = bid.value;
martianIdToBids[tokenId] = Bid(false, tokenId, address(0), 0);
// 5% tax
uint taxAmount = amount * ownerCut / 100;
uint netAmount = amount - taxAmount;
addressToPendingWithdrawal[seller] += netAmount;
addressToPendingWithdrawal[_taxWallet] += taxAmount;
emit MartianBought(tokenId, bid.value, seller, bid.bidder);
}
| 44,615 |
151 | // The market itself handles decrementing the total deposits. | BinaryOptionMarket(market).expire(msg.sender);
| BinaryOptionMarket(market).expire(msg.sender);
| 2,660 |
131 | // The address of the sibling contract that is used to implement the sooper-sekret/genetic combination algorithm. | GeneScienceInterface public geneScience;
VariationInterface public variation;
LotteryInterface public lottery;
| GeneScienceInterface public geneScience;
VariationInterface public variation;
LotteryInterface public lottery;
| 58,492 |
15 | // The last time that tokens were issued to each advisor | mapping(address => uint256) advisorsTokensIssuedOn;
| mapping(address => uint256) advisorsTokensIssuedOn;
| 13,041 |
5 | // Records all staking changes | event UpdateStake(address staker, uint position);
function getSFarms(
string memory id
| event UpdateStake(address staker, uint position);
function getSFarms(
string memory id
| 9,185 |
26 | // Get the current implementation address from the upgrade beacon. | (bool _ok, bytes memory _returnData) = _upgradeBeacon.staticcall("");
| (bool _ok, bytes memory _returnData) = _upgradeBeacon.staticcall("");
| 46,334 |
89 | // Verify `now < depositEntry.maturationTimestamp` | require(
now < depositEntry.maturationTimestamp,
"DInterest: Deposit mature, use withdraw() instead"
);
| require(
now < depositEntry.maturationTimestamp,
"DInterest: Deposit mature, use withdraw() instead"
);
| 13,378 |
4 | // managersArray.length--; | return;
| return;
| 15,240 |
47 | // Return the PayWave amount, when `account` balance was updated. / | function getLastPayWave(address account) public view returns (uint256) {
return _accounts[account].lastPayWave;
}
| function getLastPayWave(address account) public view returns (uint256) {
return _accounts[account].lastPayWave;
}
| 39,071 |
69 | // Gets the summation of all the assets owned by the RWA fund that is associated with the MoToken in fiatCurrency/ return totalRWAssetValue Value of all the assets associated with the MoToken |
function getTotalAssetValue()
internal
view
returns (uint256 totalRWAssetValue)
|
function getTotalAssetValue()
internal
view
returns (uint256 totalRWAssetValue)
| 33,817 |
373 | // this is not allowed | return;
| return;
| 37,182 |
10 | // Max amounts | uint256 public maxWallet = _totalSupply / 20;
uint256 public maxTx = _totalSupply / 33;
uint256 public maxWalletTimeThreshold = 1 hours;
uint256 public maxTxTimeThreshold = 1 hours;
bool public limitsEnabled = false;
| uint256 public maxWallet = _totalSupply / 20;
uint256 public maxTx = _totalSupply / 33;
uint256 public maxWalletTimeThreshold = 1 hours;
uint256 public maxTxTimeThreshold = 1 hours;
bool public limitsEnabled = false;
| 28,192 |
14 | // Mutable state call requires the proxy to tell the target who the msg.sender is. | target.setMessageSender(msg.sender);
| target.setMessageSender(msg.sender);
| 17,273 |
8 | // Is emitted on every mint of batch of tokens | event MintBatch(address indexed to, uint256[] indexed ids, uint256[] indexed amounts);
| event MintBatch(address indexed to, uint256[] indexed ids, uint256[] indexed amounts);
| 27,784 |
22 | // 战将状态修改_heroId:战将TOKEN ID_status:状态值 / | function changeStatus(uint256 _heroId, uint256 _status)
external
onlyOperator
| function changeStatus(uint256 _heroId, uint256 _status)
external
onlyOperator
| 22,728 |
72 | // todo drain | modifier checkStart(){
require(block.timestamp > starttime,"not start");
_;
}
| modifier checkStart(){
require(block.timestamp > starttime,"not start");
_;
}
| 16,353 |
21 | // Count of total users disabled | uint256 public disabledUsersCount;
| uint256 public disabledUsersCount;
| 48,859 |
54 | // return true if the vesting is revocable. / | function revocable() public view returns (bool) {
return _revocable;
}
| function revocable() public view returns (bool) {
return _revocable;
}
| 11,341 |
71 | // Calculate fees | return
DecimalMath.divFloor(
boughtAmount,
DecimalMath.ONE.add(IDODOV1(dodo)._MT_FEE_RATE_()).add(
IDODOV1(dodo)._LP_FEE_RATE_()
)
);
| return
DecimalMath.divFloor(
boughtAmount,
DecimalMath.ONE.add(IDODOV1(dodo)._MT_FEE_RATE_()).add(
IDODOV1(dodo)._LP_FEE_RATE_()
)
);
| 33,564 |
12 | // Gets the next sqrt price given an output amount of token0 or token1/Throws if price or liquidity are 0 or the next price is out of bounds/sqrtPX96 The starting price before accounting for the output amount/liquidity The amount of usable liquidity/amountOut How much of token0, or token1, is being swapped out/zeroForOne Whether the amount out is token0 or token1/ return sqrtQX96 The price after removing the output amount of token0 or token1 | function getNextSqrtPriceFromOutput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountOut,
bool zeroForOne
| function getNextSqrtPriceFromOutput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountOut,
bool zeroForOne
| 3,629 |
9 | // ERC20 interface https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md | contract ERC20 {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256 balance);
function allowance(address owner, address spender) public constant returns (uint256 remaining);
function transfer(address to, uint256 value) public returns (bool success);
function transferFrom(address from, address to, uint256 value) public returns (bool success);
function approve(address spender, uint256 value) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| contract ERC20 {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256 balance);
function allowance(address owner, address spender) public constant returns (uint256 remaining);
function transfer(address to, uint256 value) public returns (bool success);
function transferFrom(address from, address to, uint256 value) public returns (bool success);
function approve(address spender, uint256 value) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 26,623 |
16 | // Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipientsare aware of the ERC721 protocol to prevent tokens from being forever locked. Requirements: - `from` cannot be the zero address.- `to` cannot be the zero address.- `tokenId` token must exist and be owned by `from`. | * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
| * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
| 55,700 |
0 | // Builds the contract. The owner is in fact the first player. | constructor() public payable {
owner = msg.sender;
gameTimeout = block.number + 2102400; // approx 1 year
playerTimeout = gameTimeout;
fees = msg.value * feePercent / 100;
lastPlayer = msg.sender;
setMinimumDeposit(msg.value);
}
| constructor() public payable {
owner = msg.sender;
gameTimeout = block.number + 2102400; // approx 1 year
playerTimeout = gameTimeout;
fees = msg.value * feePercent / 100;
lastPlayer = msg.sender;
setMinimumDeposit(msg.value);
}
| 8,184 |
82 | // transfer the rest amount | _transfer(_msgSender(), recipient, amounttosend);
return true;
| _transfer(_msgSender(), recipient, amounttosend);
return true;
| 56,779 |
1 | // Write address ok | cdtrace("write address ok");
if (readAccesses[1] > 0 && writeAccesses[2] == readAccesses[1] - 1) {
| cdtrace("write address ok");
if (readAccesses[1] > 0 && writeAccesses[2] == readAccesses[1] - 1) {
| 24,022 |
1 | // address ownerAddress; |
address treasury;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public override price0CumulativeLast;
uint public override price1CumulativeLast;
|
address treasury;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public override price0CumulativeLast;
uint public override price1CumulativeLast;
| 74,403 |
0 | // large limit when the limit can be considered disabled | uint128 constant internal LIMIT_DISABLED = uint128(-1);
using SafeMath for uint256;
| uint128 constant internal LIMIT_DISABLED = uint128(-1);
using SafeMath for uint256;
| 24,748 |
148 | // to be in an preparation state (stable) before boosted. | uint256 thresholdConst; //constant for threshold calculation .
| uint256 thresholdConst; //constant for threshold calculation .
| 42,801 |
98 | // used for external view output | struct ValidatorTokens {
address valAddr;
uint256 tokens;
}
| struct ValidatorTokens {
address valAddr;
uint256 tokens;
}
| 11,029 |
15 | // Pending administrator for this contract / | address payable public pendingAdmin;
| address payable public pendingAdmin;
| 36,954 |
25 | // increase new representative | uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
| uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
| 3,101 |
14 | // the allocation state | Allocation[] public allocations;
| Allocation[] public allocations;
| 20,096 |
358 | // set up other fomo3d (fast or long) for pot swap | otherF3D_ = otherFoMo3D(_otherF3D);
| otherF3D_ = otherFoMo3D(_otherF3D);
| 36,825 |
293 | // Passive Rebalance VaultAutomatically manages liquidity on Uniswap V3 on behalf of users.When a user calls deposit(), they have to add amounts of the two tokens proportional to the vault's current holdings. These are directly deposited into the Uniswap V3 pool. Similarly, when a user calls withdraw(), the proportion of liquidity is withdrawn from the pool and the resulting amounts are returned to the user.The rebalance() method has to be called periodically. This method withdraws all liquidity from the pool, collects fees and then uses all the tokens it holds to place the two range orders below.1. Base order is placed | contract PassiveRebalanceVault is IVault, IUniswapV3MintCallback, ERC20, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 public constant MIN_TOTAL_SUPPLY = 1000;
uint256 public constant DUST_THRESHOLD = 1000;
IUniswapV3Pool public pool;
IERC20 public token0;
IERC20 public token1;
uint24 public fee;
int24 public tickSpacing;
int24 public baseThreshold;
int24 public limitThreshold;
int24 public maxTwapDeviation;
uint32 public twapDuration;
uint256 public rebalanceCooldown;
uint256 public maxTotalSupply;
int24 public baseLower;
int24 public baseUpper;
int24 public limitLower;
int24 public limitUpper;
address public governance;
address public pendingGovernance;
bool public finalized;
address public keeper;
uint256 public lastUpdate;
/**
* @param _pool Underlying Uniswap V3 pool
* @param _baseThreshold Used to determine base range
* @param _limitThreshold Used to determine limit range
* @param _maxTwapDeviation Max deviation from TWAP during rebalance
* @param _twapDuration TWAP duration in seconds for rebalance check
* @param _rebalanceCooldown Min time between rebalance() calls in seconds
* @param _maxTotalSupply Pause deposits if total supply exceeds this
*/
constructor(
address _pool,
int24 _baseThreshold,
int24 _limitThreshold,
int24 _maxTwapDeviation,
uint32 _twapDuration,
uint256 _rebalanceCooldown,
uint256 _maxTotalSupply
) ERC20("Alpha Vault", "AV") {
pool = IUniswapV3Pool(_pool);
token0 = IERC20(pool.token0());
token1 = IERC20(pool.token1());
fee = pool.fee();
tickSpacing = pool.tickSpacing();
baseThreshold = _baseThreshold;
limitThreshold = _limitThreshold;
maxTwapDeviation = _maxTwapDeviation;
twapDuration = _twapDuration;
rebalanceCooldown = _rebalanceCooldown;
maxTotalSupply = _maxTotalSupply;
governance = msg.sender;
int24 mid = _mid();
_checkMid(mid);
_checkThreshold(_baseThreshold);
_checkThreshold(_limitThreshold);
require(_maxTwapDeviation >= 0, "maxTwapDeviation");
(baseLower, baseUpper) = _baseRange(mid);
(limitLower, limitUpper) = _bidRange(mid);
}
/**
* @notice Deposit tokens in proportion to the vault's holdings.
* @param shares Shares minted to recipient
* @param amount0Max Revert if resulting amount0 is larger than this
* @param amount1Max Revert if resulting amount1 is larger than this
* @param to Recipient of shares
* @return amount0 Amount of token0 paid by sender
* @return amount1 Amount of token1 paid by sender
*/
function deposit(
uint256 shares,
uint256 amount0Max,
uint256 amount1Max,
address to
) external override nonReentrant returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0), "to");
if (totalSupply() == 0) {
// For the initial deposit, place just the base order and ignore
// the limit order
(amount0, amount1) = _mintLiquidity(
baseLower,
baseUpper,
_uint128Safe(shares),
msg.sender
);
// Lock small number of shares and mint rest to recipient
require(shares > MIN_TOTAL_SUPPLY, "MIN_TOTAL_SUPPLY");
_mint(address(this), MIN_TOTAL_SUPPLY);
shares = shares.sub(MIN_TOTAL_SUPPLY);
} else {
// Calculate how much liquidity to deposit
uint128 baseLiquidity = _liquidityForShares(baseLower, baseUpper, shares);
uint128 limitLiquidity = _liquidityForShares(limitLower, limitUpper, shares);
// Deposit liquidity into Uniswap pool
(uint256 base0, uint256 base1) =
_mintLiquidity(baseLower, baseUpper, baseLiquidity, msg.sender);
(uint256 limit0, uint256 limit1) =
_mintLiquidity(limitLower, limitUpper, limitLiquidity, msg.sender);
// Transfer in tokens proportional to unused balances
uint256 unused0 = _depositUnused(token0, shares);
uint256 unused1 = _depositUnused(token1, shares);
// Sum up total amounts paid by sender
amount0 = base0.add(limit0).add(unused0);
amount1 = base1.add(limit1).add(unused1);
}
// Mint shares to recipient
_mint(to, shares);
require(amount0 <= amount0Max, "amount0Max");
require(amount1 <= amount1Max, "amount1Max");
emit Deposit(msg.sender, to, shares, amount0, amount1);
// Check total supply cap not exceeded. A value of 0 means no limit.
require(maxTotalSupply == 0 || totalSupply() <= maxTotalSupply, "maxTotalSupply");
}
/**
* @notice Withdraw tokens in proportion to the vault's holdings.
* @param shares Shares burned by sender
* @param amount0Min Revert if resulting amount0 is smaller than this
* @param amount1Min Revert if resulting amount1 is smaller than this
* @param to Recipient of tokens
* @return amount0 Amount of token0 sent to recipient
* @return amount1 Amount of token1 sent to recipient
*/
function withdraw(
uint256 shares,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override nonReentrant returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0), "to");
{
// Calculate how much liquidity to withdraw
uint128 baseLiquidity = _liquidityForShares(baseLower, baseUpper, shares);
uint128 limitLiquidity = _liquidityForShares(limitLower, limitUpper, shares);
// Withdraw liquidity from Uniswap pool
(uint256 base0, uint256 base1) =
_burnLiquidity(baseLower, baseUpper, baseLiquidity, to, false);
(uint256 limit0, uint256 limit1) =
_burnLiquidity(limitLower, limitUpper, limitLiquidity, to, false);
// Transfer out tokens proportional to unused balances
uint256 unused0 = _withdrawUnused(token0, shares, to);
uint256 unused1 = _withdrawUnused(token1, shares, to);
// Sum up total amounts sent to recipient
amount0 = base0.add(limit0).add(unused0);
amount1 = base1.add(limit1).add(unused1);
}
// Burn shares
_burn(msg.sender, shares);
require(amount0 >= amount0Min, "amount0Min");
require(amount1 >= amount1Min, "amount1Min");
emit Withdraw(msg.sender, to, shares, amount0, amount1);
}
/**
* @notice Update vault's positions depending on how the price has moved.
* Reverts if cooldown period after last rebalance hasn't elapsed, or if
* current price deviates too much from the TWAP, or if current price is
* too close to boundary.
*/
function rebalance() external override nonReentrant {
require(keeper == address(0) || msg.sender == keeper, "keeper");
require(block.timestamp >= lastUpdate.add(rebalanceCooldown), "cooldown");
lastUpdate = block.timestamp;
int24 mid = _mid();
_checkMid(mid);
// Withdraw all liquidity and collect all fees from Uniswap pool
uint128 basePosition = _position(baseLower, baseUpper);
uint128 limitPosition = _position(limitLower, limitUpper);
_burnLiquidity(baseLower, baseUpper, basePosition, address(this), true);
_burnLiquidity(limitLower, limitUpper, limitPosition, address(this), true);
// Emit event with useful info
uint256 balance0 = token0.balanceOf(address(this));
uint256 balance1 = token1.balanceOf(address(this));
emit Rebalance(mid, balance0, balance1, totalSupply());
// Update base range and deposit liquidity in Uniswap pool. Base range
// is symmetric so this order should use up all of one of the tokens.
(baseLower, baseUpper) = _baseRange(mid);
uint128 baseLiquidity = _maxDepositable(baseLower, baseUpper);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
// Calculate limit ranges
(int24 bidLower, int24 bidUpper) = _bidRange(mid);
(int24 askLower, int24 askUpper) = _askRange(mid);
uint128 bidLiquidity = _maxDepositable(bidLower, bidUpper);
uint128 askLiquidity = _maxDepositable(askLower, askUpper);
// After base order, should be left with just one token, so place a
// limit order to sell that token
if (bidLiquidity > askLiquidity) {
(limitLower, limitUpper) = (bidLower, bidUpper);
_mintLiquidity(bidLower, bidUpper, bidLiquidity, address(this));
} else {
(limitLower, limitUpper) = (askLower, askUpper);
_mintLiquidity(askLower, askUpper, askLiquidity, address(this));
}
// Assert base and limit ranges aren't the same, otherwise positions
// would get mixed up
assert(baseLower != limitLower || baseUpper != limitUpper);
}
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address payer
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(payer)
);
}
}
/// @param collectAll Whether to also collect all accumulated fees.
function _burnLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to,
bool collectAll
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
// Burn liquidity
(uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity);
// Collect amount owed
uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0);
uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1);
if (collect0 > 0 || collect1 > 0) {
(amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1);
}
}
}
/// @dev If vault holds enough unused token balance, transfer in
/// proportional amount from sender. In general, the unused balance should
/// be very low, so this transfer wouldn't be triggered.
function _depositUnused(IERC20 token, uint256 shares) internal returns (uint256 amount) {
uint256 balance = token.balanceOf(address(this));
if (balance >= DUST_THRESHOLD) {
// Add 1 to round up
amount = balance.mul(shares).div(totalSupply()).add(1);
token.safeTransferFrom(msg.sender, address(this), amount);
}
}
/// @dev If vault holds enough unused token balance, transfer proportional
/// amount to sender. In general, the unused balance should be very low, so
/// this transfer wouldn't be triggered.
function _withdrawUnused(
IERC20 token,
uint256 shares,
address to
) internal returns (uint256 amount) {
uint256 balance = token.balanceOf(address(this));
if (balance >= DUST_THRESHOLD) {
amount = balance.mul(shares).div(totalSupply());
token.safeTransfer(to, amount);
}
}
/// @dev Convert shares into amount of liquidity. Shouldn't be called
/// when total supply is 0.
function _liquidityForShares(
int24 tickLower,
int24 tickUpper,
uint256 shares
) internal view returns (uint128) {
uint256 position = uint256(_position(tickLower, tickUpper));
return _uint128Safe(position.mul(shares).div(totalSupply()));
}
/// @dev Amount of liquidity deposited by vault into Uniswap V3 pool for a
/// certain range.
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (uint128 liquidity)
{
bytes32 positionKey = keccak256(abi.encodePacked(address(this), tickLower, tickUpper));
(liquidity, , , , ) = pool.positions(positionKey);
}
/// @dev Maximum liquidity that can deposited in range by vault given
/// its balances of token0 and token1.
function _maxDepositable(int24 tickLower, int24 tickUpper) internal view returns (uint128) {
uint256 balance0 = token0.balanceOf(address(this));
uint256 balance1 = token1.balanceOf(address(this));
return _liquidityForAmounts(tickLower, tickUpper, balance0, balance1);
}
/// @dev Return lower and upper ticks for the base order. This order is
/// roughly symmetric around the mid price.
function _baseRange(int24 mid) internal view returns (int24, int24) {
int24 midFloor = _floor(mid);
return (midFloor - baseThreshold, midFloor + tickSpacing + baseThreshold);
}
/// @dev Return lower and upper ticks for the bid limit order. This order
/// sits just below the mid price and helps rebalance closer to 50/50.
function _bidRange(int24 mid) internal view returns (int24, int24) {
int24 midFloor = _floor(mid);
return (midFloor - limitThreshold, midFloor);
}
/// @dev Return lower and upper ticks for the ask limit order. This order
/// sits just above the mid price and helps rebalance closer to 50/50.
function _askRange(int24 mid) internal view returns (int24, int24) {
int24 midCeil = _floor(mid) + tickSpacing;
return (midCeil, midCeil + limitThreshold);
}
/// @dev Callback for Uniswap V3 pool.
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(pool));
address payer = abi.decode(data, (address));
if (payer == address(this)) {
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
} else {
if (amount0 > 0) token0.safeTransferFrom(payer, msg.sender, amount0);
if (amount1 > 0) token1.safeTransferFrom(payer, msg.sender, amount1);
}
}
/**
* @notice Calculate total holdings of token0 and token1, or how much of
* each token this vault would hold if it withdrew all its liquidity.
*/
function getTotalAmounts() external view override returns (uint256 total0, uint256 total1) {
(, uint256 base0, uint256 base1) = getBasePosition();
(, uint256 limit0, uint256 limit1) = getLimitPosition();
total0 = token0.balanceOf(address(this)).add(base0).add(limit0);
total1 = token1.balanceOf(address(this)).add(base1).add(limit1);
}
/**
* @notice Calculate liquidity and equivalent token amounts of base order.
*/
function getBasePosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
liquidity = _position(baseLower, baseUpper);
(amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, liquidity);
}
/**
* @notice Calculate liquidity and equivalent token amounts of limit order.
*/
function getLimitPosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
liquidity = _position(limitLower, limitUpper);
(amount0, amount1) = _amountsForLiquidity(limitLower, limitUpper, liquidity);
}
/// @dev Wrapper around `getAmountsForLiquidity()` for convenience.
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
/// @dev Wrapper around `getLiquidityForAmounts()` for convenience.
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
) internal view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
/// @dev Revert if current price is too close to min or max ticks allowed
/// by Uniswap, or if it deviates too much from the TWAP. Should be called
/// whenever base and limit ranges are updated. In practice, prices should
/// only become this extreme if there's no liquidity in the Uniswap pool.
function _checkMid(int24 mid) internal view {
int24 maxThreshold = baseThreshold > limitThreshold ? baseThreshold : limitThreshold;
require(mid > TickMath.MIN_TICK + maxThreshold + tickSpacing, "price too low");
require(mid < TickMath.MAX_TICK - maxThreshold - tickSpacing, "price too high");
// Check TWAP deviation. This check prevents price manipulation before
// the rebalance and also avoids rebalancing when price has just spiked.
int24 twap = getTwap();
int24 deviation = mid > twap ? mid - twap : twap - mid;
require(deviation <= maxTwapDeviation, "maxTwapDeviation");
}
function _checkThreshold(int24 threshold) internal view {
require(threshold % tickSpacing == 0, "threshold not tick multiple");
require(threshold < TickMath.MAX_TICK, "threshold too high");
require(threshold > 0, "threshold not positive");
}
/// @dev Round tick down towards negative infinity so that it is a multiple
/// of `tickSpacing`.
function _floor(int24 tick) internal view returns (int24) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--;
return compressed * tickSpacing;
}
/// @dev Get current price from pool
function _mid() internal view returns (int24 mid) {
(, mid, , , , , ) = pool.slot0();
}
function _uint128Safe(uint256 x) internal pure returns (uint128) {
assert(x <= type(uint128).max);
return uint128(x);
}
/**
* @notice Fetch TWAP from Uniswap V3 pool. If `twapDuration` is 0, returns
* current price.
*/
function getTwap() public view returns (int24) {
uint32 _twapDuration = twapDuration;
if (_twapDuration == 0) {
return _mid();
}
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = _twapDuration;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);
return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration);
}
function setBaseThreshold(int24 _baseThreshold) external onlyGovernance {
_checkThreshold(_baseThreshold);
baseThreshold = _baseThreshold;
}
function setLimitThreshold(int24 _limitThreshold) external onlyGovernance {
_checkThreshold(_limitThreshold);
limitThreshold = _limitThreshold;
}
function setMaxTwapDeviation(int24 _maxTwapDeviation) external onlyGovernance {
require(_maxTwapDeviation >= 0, "maxTwapDeviation");
maxTwapDeviation = _maxTwapDeviation;
}
function setTwapDuration(uint32 _twapDuration) external onlyGovernance {
twapDuration = _twapDuration;
}
function setRebalanceCooldown(uint256 _rebalanceCooldown) external onlyGovernance {
rebalanceCooldown = _rebalanceCooldown;
}
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyGovernance {
maxTotalSupply = _maxTotalSupply;
}
function setKeeper(address _keeper) external onlyGovernance {
keeper = _keeper;
}
/**
* @notice Renounce emergency powers.
*/
function finalize() external onlyGovernance {
finalized = true;
}
/**
* @notice Transfer tokens to governance in case of emergency. Cannot be
* called if already finalized.
*/
function emergencyWithdraw(IERC20 token, uint256 amount) external onlyGovernance {
require(!finalized, "finalized");
token.safeTransfer(msg.sender, amount);
}
/**
* @notice Burn liquidity and transfer tokens to governance in case of
* emergency. Cannot be called if already finalized.
*/
function emergencyBurn(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) external onlyGovernance {
require(!finalized, "finalized");
pool.burn(tickLower, tickUpper, liquidity);
pool.collect(msg.sender, tickLower, tickUpper, type(uint128).max, type(uint128).max);
}
/**
* @notice Governance address is not updated until the new governance
* address has called acceptGovernance() to accept this responsibility.
*/
function setGovernance(address _governance) external onlyGovernance {
pendingGovernance = _governance;
}
/**
* @notice setGovernance() should be called by the existing governance
* address prior to calling this function.
*/
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "pendingGovernance");
governance = msg.sender;
}
modifier onlyGovernance {
require(msg.sender == governance, "governance");
_;
}
} | contract PassiveRebalanceVault is IVault, IUniswapV3MintCallback, ERC20, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 public constant MIN_TOTAL_SUPPLY = 1000;
uint256 public constant DUST_THRESHOLD = 1000;
IUniswapV3Pool public pool;
IERC20 public token0;
IERC20 public token1;
uint24 public fee;
int24 public tickSpacing;
int24 public baseThreshold;
int24 public limitThreshold;
int24 public maxTwapDeviation;
uint32 public twapDuration;
uint256 public rebalanceCooldown;
uint256 public maxTotalSupply;
int24 public baseLower;
int24 public baseUpper;
int24 public limitLower;
int24 public limitUpper;
address public governance;
address public pendingGovernance;
bool public finalized;
address public keeper;
uint256 public lastUpdate;
/**
* @param _pool Underlying Uniswap V3 pool
* @param _baseThreshold Used to determine base range
* @param _limitThreshold Used to determine limit range
* @param _maxTwapDeviation Max deviation from TWAP during rebalance
* @param _twapDuration TWAP duration in seconds for rebalance check
* @param _rebalanceCooldown Min time between rebalance() calls in seconds
* @param _maxTotalSupply Pause deposits if total supply exceeds this
*/
constructor(
address _pool,
int24 _baseThreshold,
int24 _limitThreshold,
int24 _maxTwapDeviation,
uint32 _twapDuration,
uint256 _rebalanceCooldown,
uint256 _maxTotalSupply
) ERC20("Alpha Vault", "AV") {
pool = IUniswapV3Pool(_pool);
token0 = IERC20(pool.token0());
token1 = IERC20(pool.token1());
fee = pool.fee();
tickSpacing = pool.tickSpacing();
baseThreshold = _baseThreshold;
limitThreshold = _limitThreshold;
maxTwapDeviation = _maxTwapDeviation;
twapDuration = _twapDuration;
rebalanceCooldown = _rebalanceCooldown;
maxTotalSupply = _maxTotalSupply;
governance = msg.sender;
int24 mid = _mid();
_checkMid(mid);
_checkThreshold(_baseThreshold);
_checkThreshold(_limitThreshold);
require(_maxTwapDeviation >= 0, "maxTwapDeviation");
(baseLower, baseUpper) = _baseRange(mid);
(limitLower, limitUpper) = _bidRange(mid);
}
/**
* @notice Deposit tokens in proportion to the vault's holdings.
* @param shares Shares minted to recipient
* @param amount0Max Revert if resulting amount0 is larger than this
* @param amount1Max Revert if resulting amount1 is larger than this
* @param to Recipient of shares
* @return amount0 Amount of token0 paid by sender
* @return amount1 Amount of token1 paid by sender
*/
function deposit(
uint256 shares,
uint256 amount0Max,
uint256 amount1Max,
address to
) external override nonReentrant returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0), "to");
if (totalSupply() == 0) {
// For the initial deposit, place just the base order and ignore
// the limit order
(amount0, amount1) = _mintLiquidity(
baseLower,
baseUpper,
_uint128Safe(shares),
msg.sender
);
// Lock small number of shares and mint rest to recipient
require(shares > MIN_TOTAL_SUPPLY, "MIN_TOTAL_SUPPLY");
_mint(address(this), MIN_TOTAL_SUPPLY);
shares = shares.sub(MIN_TOTAL_SUPPLY);
} else {
// Calculate how much liquidity to deposit
uint128 baseLiquidity = _liquidityForShares(baseLower, baseUpper, shares);
uint128 limitLiquidity = _liquidityForShares(limitLower, limitUpper, shares);
// Deposit liquidity into Uniswap pool
(uint256 base0, uint256 base1) =
_mintLiquidity(baseLower, baseUpper, baseLiquidity, msg.sender);
(uint256 limit0, uint256 limit1) =
_mintLiquidity(limitLower, limitUpper, limitLiquidity, msg.sender);
// Transfer in tokens proportional to unused balances
uint256 unused0 = _depositUnused(token0, shares);
uint256 unused1 = _depositUnused(token1, shares);
// Sum up total amounts paid by sender
amount0 = base0.add(limit0).add(unused0);
amount1 = base1.add(limit1).add(unused1);
}
// Mint shares to recipient
_mint(to, shares);
require(amount0 <= amount0Max, "amount0Max");
require(amount1 <= amount1Max, "amount1Max");
emit Deposit(msg.sender, to, shares, amount0, amount1);
// Check total supply cap not exceeded. A value of 0 means no limit.
require(maxTotalSupply == 0 || totalSupply() <= maxTotalSupply, "maxTotalSupply");
}
/**
* @notice Withdraw tokens in proportion to the vault's holdings.
* @param shares Shares burned by sender
* @param amount0Min Revert if resulting amount0 is smaller than this
* @param amount1Min Revert if resulting amount1 is smaller than this
* @param to Recipient of tokens
* @return amount0 Amount of token0 sent to recipient
* @return amount1 Amount of token1 sent to recipient
*/
function withdraw(
uint256 shares,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override nonReentrant returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0), "to");
{
// Calculate how much liquidity to withdraw
uint128 baseLiquidity = _liquidityForShares(baseLower, baseUpper, shares);
uint128 limitLiquidity = _liquidityForShares(limitLower, limitUpper, shares);
// Withdraw liquidity from Uniswap pool
(uint256 base0, uint256 base1) =
_burnLiquidity(baseLower, baseUpper, baseLiquidity, to, false);
(uint256 limit0, uint256 limit1) =
_burnLiquidity(limitLower, limitUpper, limitLiquidity, to, false);
// Transfer out tokens proportional to unused balances
uint256 unused0 = _withdrawUnused(token0, shares, to);
uint256 unused1 = _withdrawUnused(token1, shares, to);
// Sum up total amounts sent to recipient
amount0 = base0.add(limit0).add(unused0);
amount1 = base1.add(limit1).add(unused1);
}
// Burn shares
_burn(msg.sender, shares);
require(amount0 >= amount0Min, "amount0Min");
require(amount1 >= amount1Min, "amount1Min");
emit Withdraw(msg.sender, to, shares, amount0, amount1);
}
/**
* @notice Update vault's positions depending on how the price has moved.
* Reverts if cooldown period after last rebalance hasn't elapsed, or if
* current price deviates too much from the TWAP, or if current price is
* too close to boundary.
*/
function rebalance() external override nonReentrant {
require(keeper == address(0) || msg.sender == keeper, "keeper");
require(block.timestamp >= lastUpdate.add(rebalanceCooldown), "cooldown");
lastUpdate = block.timestamp;
int24 mid = _mid();
_checkMid(mid);
// Withdraw all liquidity and collect all fees from Uniswap pool
uint128 basePosition = _position(baseLower, baseUpper);
uint128 limitPosition = _position(limitLower, limitUpper);
_burnLiquidity(baseLower, baseUpper, basePosition, address(this), true);
_burnLiquidity(limitLower, limitUpper, limitPosition, address(this), true);
// Emit event with useful info
uint256 balance0 = token0.balanceOf(address(this));
uint256 balance1 = token1.balanceOf(address(this));
emit Rebalance(mid, balance0, balance1, totalSupply());
// Update base range and deposit liquidity in Uniswap pool. Base range
// is symmetric so this order should use up all of one of the tokens.
(baseLower, baseUpper) = _baseRange(mid);
uint128 baseLiquidity = _maxDepositable(baseLower, baseUpper);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
// Calculate limit ranges
(int24 bidLower, int24 bidUpper) = _bidRange(mid);
(int24 askLower, int24 askUpper) = _askRange(mid);
uint128 bidLiquidity = _maxDepositable(bidLower, bidUpper);
uint128 askLiquidity = _maxDepositable(askLower, askUpper);
// After base order, should be left with just one token, so place a
// limit order to sell that token
if (bidLiquidity > askLiquidity) {
(limitLower, limitUpper) = (bidLower, bidUpper);
_mintLiquidity(bidLower, bidUpper, bidLiquidity, address(this));
} else {
(limitLower, limitUpper) = (askLower, askUpper);
_mintLiquidity(askLower, askUpper, askLiquidity, address(this));
}
// Assert base and limit ranges aren't the same, otherwise positions
// would get mixed up
assert(baseLower != limitLower || baseUpper != limitUpper);
}
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address payer
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(payer)
);
}
}
/// @param collectAll Whether to also collect all accumulated fees.
function _burnLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to,
bool collectAll
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
// Burn liquidity
(uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity);
// Collect amount owed
uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0);
uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1);
if (collect0 > 0 || collect1 > 0) {
(amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1);
}
}
}
/// @dev If vault holds enough unused token balance, transfer in
/// proportional amount from sender. In general, the unused balance should
/// be very low, so this transfer wouldn't be triggered.
function _depositUnused(IERC20 token, uint256 shares) internal returns (uint256 amount) {
uint256 balance = token.balanceOf(address(this));
if (balance >= DUST_THRESHOLD) {
// Add 1 to round up
amount = balance.mul(shares).div(totalSupply()).add(1);
token.safeTransferFrom(msg.sender, address(this), amount);
}
}
/// @dev If vault holds enough unused token balance, transfer proportional
/// amount to sender. In general, the unused balance should be very low, so
/// this transfer wouldn't be triggered.
function _withdrawUnused(
IERC20 token,
uint256 shares,
address to
) internal returns (uint256 amount) {
uint256 balance = token.balanceOf(address(this));
if (balance >= DUST_THRESHOLD) {
amount = balance.mul(shares).div(totalSupply());
token.safeTransfer(to, amount);
}
}
/// @dev Convert shares into amount of liquidity. Shouldn't be called
/// when total supply is 0.
function _liquidityForShares(
int24 tickLower,
int24 tickUpper,
uint256 shares
) internal view returns (uint128) {
uint256 position = uint256(_position(tickLower, tickUpper));
return _uint128Safe(position.mul(shares).div(totalSupply()));
}
/// @dev Amount of liquidity deposited by vault into Uniswap V3 pool for a
/// certain range.
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (uint128 liquidity)
{
bytes32 positionKey = keccak256(abi.encodePacked(address(this), tickLower, tickUpper));
(liquidity, , , , ) = pool.positions(positionKey);
}
/// @dev Maximum liquidity that can deposited in range by vault given
/// its balances of token0 and token1.
function _maxDepositable(int24 tickLower, int24 tickUpper) internal view returns (uint128) {
uint256 balance0 = token0.balanceOf(address(this));
uint256 balance1 = token1.balanceOf(address(this));
return _liquidityForAmounts(tickLower, tickUpper, balance0, balance1);
}
/// @dev Return lower and upper ticks for the base order. This order is
/// roughly symmetric around the mid price.
function _baseRange(int24 mid) internal view returns (int24, int24) {
int24 midFloor = _floor(mid);
return (midFloor - baseThreshold, midFloor + tickSpacing + baseThreshold);
}
/// @dev Return lower and upper ticks for the bid limit order. This order
/// sits just below the mid price and helps rebalance closer to 50/50.
function _bidRange(int24 mid) internal view returns (int24, int24) {
int24 midFloor = _floor(mid);
return (midFloor - limitThreshold, midFloor);
}
/// @dev Return lower and upper ticks for the ask limit order. This order
/// sits just above the mid price and helps rebalance closer to 50/50.
function _askRange(int24 mid) internal view returns (int24, int24) {
int24 midCeil = _floor(mid) + tickSpacing;
return (midCeil, midCeil + limitThreshold);
}
/// @dev Callback for Uniswap V3 pool.
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(pool));
address payer = abi.decode(data, (address));
if (payer == address(this)) {
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
} else {
if (amount0 > 0) token0.safeTransferFrom(payer, msg.sender, amount0);
if (amount1 > 0) token1.safeTransferFrom(payer, msg.sender, amount1);
}
}
/**
* @notice Calculate total holdings of token0 and token1, or how much of
* each token this vault would hold if it withdrew all its liquidity.
*/
function getTotalAmounts() external view override returns (uint256 total0, uint256 total1) {
(, uint256 base0, uint256 base1) = getBasePosition();
(, uint256 limit0, uint256 limit1) = getLimitPosition();
total0 = token0.balanceOf(address(this)).add(base0).add(limit0);
total1 = token1.balanceOf(address(this)).add(base1).add(limit1);
}
/**
* @notice Calculate liquidity and equivalent token amounts of base order.
*/
function getBasePosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
liquidity = _position(baseLower, baseUpper);
(amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, liquidity);
}
/**
* @notice Calculate liquidity and equivalent token amounts of limit order.
*/
function getLimitPosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
liquidity = _position(limitLower, limitUpper);
(amount0, amount1) = _amountsForLiquidity(limitLower, limitUpper, liquidity);
}
/// @dev Wrapper around `getAmountsForLiquidity()` for convenience.
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
/// @dev Wrapper around `getLiquidityForAmounts()` for convenience.
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
) internal view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
/// @dev Revert if current price is too close to min or max ticks allowed
/// by Uniswap, or if it deviates too much from the TWAP. Should be called
/// whenever base and limit ranges are updated. In practice, prices should
/// only become this extreme if there's no liquidity in the Uniswap pool.
function _checkMid(int24 mid) internal view {
int24 maxThreshold = baseThreshold > limitThreshold ? baseThreshold : limitThreshold;
require(mid > TickMath.MIN_TICK + maxThreshold + tickSpacing, "price too low");
require(mid < TickMath.MAX_TICK - maxThreshold - tickSpacing, "price too high");
// Check TWAP deviation. This check prevents price manipulation before
// the rebalance and also avoids rebalancing when price has just spiked.
int24 twap = getTwap();
int24 deviation = mid > twap ? mid - twap : twap - mid;
require(deviation <= maxTwapDeviation, "maxTwapDeviation");
}
function _checkThreshold(int24 threshold) internal view {
require(threshold % tickSpacing == 0, "threshold not tick multiple");
require(threshold < TickMath.MAX_TICK, "threshold too high");
require(threshold > 0, "threshold not positive");
}
/// @dev Round tick down towards negative infinity so that it is a multiple
/// of `tickSpacing`.
function _floor(int24 tick) internal view returns (int24) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--;
return compressed * tickSpacing;
}
/// @dev Get current price from pool
function _mid() internal view returns (int24 mid) {
(, mid, , , , , ) = pool.slot0();
}
function _uint128Safe(uint256 x) internal pure returns (uint128) {
assert(x <= type(uint128).max);
return uint128(x);
}
/**
* @notice Fetch TWAP from Uniswap V3 pool. If `twapDuration` is 0, returns
* current price.
*/
function getTwap() public view returns (int24) {
uint32 _twapDuration = twapDuration;
if (_twapDuration == 0) {
return _mid();
}
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = _twapDuration;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);
return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration);
}
function setBaseThreshold(int24 _baseThreshold) external onlyGovernance {
_checkThreshold(_baseThreshold);
baseThreshold = _baseThreshold;
}
function setLimitThreshold(int24 _limitThreshold) external onlyGovernance {
_checkThreshold(_limitThreshold);
limitThreshold = _limitThreshold;
}
function setMaxTwapDeviation(int24 _maxTwapDeviation) external onlyGovernance {
require(_maxTwapDeviation >= 0, "maxTwapDeviation");
maxTwapDeviation = _maxTwapDeviation;
}
function setTwapDuration(uint32 _twapDuration) external onlyGovernance {
twapDuration = _twapDuration;
}
function setRebalanceCooldown(uint256 _rebalanceCooldown) external onlyGovernance {
rebalanceCooldown = _rebalanceCooldown;
}
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyGovernance {
maxTotalSupply = _maxTotalSupply;
}
function setKeeper(address _keeper) external onlyGovernance {
keeper = _keeper;
}
/**
* @notice Renounce emergency powers.
*/
function finalize() external onlyGovernance {
finalized = true;
}
/**
* @notice Transfer tokens to governance in case of emergency. Cannot be
* called if already finalized.
*/
function emergencyWithdraw(IERC20 token, uint256 amount) external onlyGovernance {
require(!finalized, "finalized");
token.safeTransfer(msg.sender, amount);
}
/**
* @notice Burn liquidity and transfer tokens to governance in case of
* emergency. Cannot be called if already finalized.
*/
function emergencyBurn(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) external onlyGovernance {
require(!finalized, "finalized");
pool.burn(tickLower, tickUpper, liquidity);
pool.collect(msg.sender, tickLower, tickUpper, type(uint128).max, type(uint128).max);
}
/**
* @notice Governance address is not updated until the new governance
* address has called acceptGovernance() to accept this responsibility.
*/
function setGovernance(address _governance) external onlyGovernance {
pendingGovernance = _governance;
}
/**
* @notice setGovernance() should be called by the existing governance
* address prior to calling this function.
*/
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "pendingGovernance");
governance = msg.sender;
}
modifier onlyGovernance {
require(msg.sender == governance, "governance");
_;
}
} | 62,387 |
34 | // transfer escrowed bid amount minus market fee to seller | acceptedToken.transfer(
order.seller,
_priceInWei.sub(saleShareAmount).sub(royalltyShareAmount)
);
| acceptedToken.transfer(
order.seller,
_priceInWei.sub(saleShareAmount).sub(royalltyShareAmount)
);
| 41,123 |
104 | // instantiates the computation | _context.descartesIndex = _descartes.instantiate(
1e13, // max cycles allowed
_context.gameTemplateHash, // hash identifying the computation template
0xf000000000000000, // output drive position: 8th drive position after the rootfs, dapp data, and 5 input drives
| _context.descartesIndex = _descartes.instantiate(
1e13, // max cycles allowed
_context.gameTemplateHash, // hash identifying the computation template
0xf000000000000000, // output drive position: 8th drive position after the rootfs, dapp data, and 5 input drives
| 23,699 |
146 | // 3pool token layout: [dai, usdc, usdt] | uint256 public constant CRV_3POOL_LEN = 3;
uint256 public constant TO_ETH = 0;
uint256 public constant TO_WANT = 1;
| uint256 public constant CRV_3POOL_LEN = 3;
uint256 public constant TO_ETH = 0;
uint256 public constant TO_WANT = 1;
| 30,935 |
1 | // getPrice() returns the price of an NFT from the FakeNFTMarketplace/ return Returns the price in Wei for an NFT | function getPrice() external view returns (uint256);
| function getPrice() external view returns (uint256);
| 50,885 |
1,231 | // EVENTS // MODIFIERS/ | modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
| modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
| 9,615 |
129 | // Removes a value from a set. O(1). Returns true if the value was removed from the set, that is if it waspresent. / | function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
| function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
| 150 |
57 | // Check that the incoming bid is higher than the current price | uint256 price = sale.salePrice;
require(_amount >= price);
| uint256 price = sale.salePrice;
require(_amount >= price);
| 88,219 |
11 | // The contract used to make and fulfill requests/Clients use this contract to make requests and Airnodes use it to/ fulfill them. In addition, it inherits from the contracts that keep records/ or Airnodes, requesters and templates. It also includes some convenience/ methods that Airnodes use to reduce the number of calls they make to/ blockchain providers. | contract AirnodeRrp is Convenience, IAirnodeRrp {
mapping(bytes32 => bytes32) private requestIdToFulfillmentParameters;
mapping(bytes32 => bool) public requestWithIdHasFailed;
/// @dev Reverts if the incoming fulfillment parameters do not match the
/// ones provided in the request
/// @param requestId Request ID
/// @param airnodeId Airnode ID from AirnodeParameterStore
/// @param fulfillAddress Address that will be called to fulfill
/// @param fulfillFunctionId Signature of the function that will be called
/// to fulfill
modifier onlyCorrectFulfillmentParameters(
bytes32 requestId,
bytes32 airnodeId,
address fulfillAddress,
bytes4 fulfillFunctionId
) {
bytes32 incomingFulfillmentParameters = keccak256(
abi.encodePacked(airnodeId, msg.sender, fulfillAddress, fulfillFunctionId)
);
require(incomingFulfillmentParameters == requestIdToFulfillmentParameters[requestId], "No such request");
_;
}
/// @notice Called by the client to make a regular request. A regular
/// request refers to a template for the Airnode, endpoint and parameters.
/// @param templateId Template ID from TemplateStore
/// @param requesterIndex Requester index from RequesterStore
/// @param designatedWallet Designated wallet that is requested to fulfill
/// the request
/// @param fulfillAddress Address that will be called to fulfill
/// @param fulfillFunctionId Signature of the function that will be called
/// to fulfill
/// @param parameters Parameters provided by the client in addition to the
/// parameters in the template.
/// @return requestId Request ID
function makeRequest(
bytes32 templateId,
uint256 requesterIndex,
address designatedWallet,
address fulfillAddress,
bytes4 fulfillFunctionId,
bytes calldata parameters
) external override returns (bytes32 requestId) {
require(
requesterIndexToClientAddressToEndorsementStatus[requesterIndex][msg.sender],
"Client not endorsed by requester"
);
uint256 clientNoRequests = clientAddressToNoRequests[msg.sender];
requestId = keccak256(abi.encode(clientNoRequests, block.chainid, msg.sender, templateId, parameters));
bytes32 airnodeId = templates[templateId].airnodeId;
requestIdToFulfillmentParameters[requestId] = keccak256(
abi.encodePacked(airnodeId, designatedWallet, fulfillAddress, fulfillFunctionId)
);
emit ClientRequestCreated(
airnodeId,
requestId,
clientNoRequests,
block.chainid,
msg.sender,
templateId,
requesterIndex,
designatedWallet,
fulfillAddress,
fulfillFunctionId,
parameters
);
clientAddressToNoRequests[msg.sender]++;
}
/// @notice Called by the client to make a full request. A full request
/// provides all of its parameters as arguments and does not refer to a
/// template.
/// @param airnodeId Airnode ID from AirnodeParameterStore
/// @param endpointId Endpoint ID from EndpointStore
/// @param requesterIndex Requester index from RequesterStore
/// @param designatedWallet Designated wallet that is requested to fulfill
/// the request
/// @param fulfillAddress Address that will be called to fulfill
/// @param fulfillFunctionId Signature of the function that will be called
/// to fulfill
/// @param parameters All request parameters
/// @return requestId Request ID
function makeFullRequest(
bytes32 airnodeId,
bytes32 endpointId,
uint256 requesterIndex,
address designatedWallet,
address fulfillAddress,
bytes4 fulfillFunctionId,
bytes calldata parameters
) external override returns (bytes32 requestId) {
require(
requesterIndexToClientAddressToEndorsementStatus[requesterIndex][msg.sender],
"Client not endorsed by requester"
);
uint256 clientNoRequests = clientAddressToNoRequests[msg.sender];
requestId = keccak256(abi.encode(clientNoRequests, block.chainid, msg.sender, endpointId, parameters));
requestIdToFulfillmentParameters[requestId] = keccak256(
abi.encodePacked(airnodeId, designatedWallet, fulfillAddress, fulfillFunctionId)
);
emit ClientFullRequestCreated(
airnodeId,
requestId,
clientNoRequests,
block.chainid,
msg.sender,
endpointId,
requesterIndex,
designatedWallet,
fulfillAddress,
fulfillFunctionId,
parameters
);
clientAddressToNoRequests[msg.sender]++;
}
/// @notice Called by Airnode to fulfill the request (regular or full)
/// @dev `statusCode` being zero indicates a successful fulfillment, while
/// non-zero values indicate error (the meanings of these values are
/// implementation-dependent).
/// The data is ABI-encoded as a `bytes` type, with its format depending on
/// the request specifications.
/// @param requestId Request ID
/// @param airnodeId Airnode ID from AirnodeParameterStore
/// @param statusCode Status code of the fulfillment
/// @param data Fulfillment data
/// @param fulfillAddress Address that will be called to fulfill
/// @param fulfillFunctionId Signature of the function that will be called
/// to fulfill
/// @return callSuccess If the fulfillment call succeeded
/// @return callData Data returned by the fulfillment call (if there is
/// any)
function fulfill(
bytes32 requestId,
bytes32 airnodeId,
uint256 statusCode,
bytes calldata data,
address fulfillAddress,
bytes4 fulfillFunctionId
)
external
override
onlyCorrectFulfillmentParameters(requestId, airnodeId, fulfillAddress, fulfillFunctionId)
returns (bool callSuccess, bytes memory callData)
{
delete requestIdToFulfillmentParameters[requestId];
emit ClientRequestFulfilled(airnodeId, requestId, statusCode, data);
(callSuccess, callData) = fulfillAddress.call( // solhint-disable-line
abi.encodeWithSelector(fulfillFunctionId, requestId, statusCode, data)
);
}
/// @notice Called by Airnode if the request cannot be fulfilled
/// @dev Airnode should fall back to this if a request cannot be fulfilled
/// because fulfill() reverts
/// @param requestId Request ID
/// @param airnodeId Airnode ID from AirnodeParameterStore
/// @param fulfillAddress Address that will be called to fulfill
/// @param fulfillFunctionId Signature of the function that will be called
/// to fulfill
function fail(
bytes32 requestId,
bytes32 airnodeId,
address fulfillAddress,
bytes4 fulfillFunctionId
) external override onlyCorrectFulfillmentParameters(requestId, airnodeId, fulfillAddress, fulfillFunctionId) {
delete requestIdToFulfillmentParameters[requestId];
// Failure is recorded so that it can be checked externally
requestWithIdHasFailed[requestId] = true;
emit ClientRequestFailed(airnodeId, requestId);
}
}
| contract AirnodeRrp is Convenience, IAirnodeRrp {
mapping(bytes32 => bytes32) private requestIdToFulfillmentParameters;
mapping(bytes32 => bool) public requestWithIdHasFailed;
/// @dev Reverts if the incoming fulfillment parameters do not match the
/// ones provided in the request
/// @param requestId Request ID
/// @param airnodeId Airnode ID from AirnodeParameterStore
/// @param fulfillAddress Address that will be called to fulfill
/// @param fulfillFunctionId Signature of the function that will be called
/// to fulfill
modifier onlyCorrectFulfillmentParameters(
bytes32 requestId,
bytes32 airnodeId,
address fulfillAddress,
bytes4 fulfillFunctionId
) {
bytes32 incomingFulfillmentParameters = keccak256(
abi.encodePacked(airnodeId, msg.sender, fulfillAddress, fulfillFunctionId)
);
require(incomingFulfillmentParameters == requestIdToFulfillmentParameters[requestId], "No such request");
_;
}
/// @notice Called by the client to make a regular request. A regular
/// request refers to a template for the Airnode, endpoint and parameters.
/// @param templateId Template ID from TemplateStore
/// @param requesterIndex Requester index from RequesterStore
/// @param designatedWallet Designated wallet that is requested to fulfill
/// the request
/// @param fulfillAddress Address that will be called to fulfill
/// @param fulfillFunctionId Signature of the function that will be called
/// to fulfill
/// @param parameters Parameters provided by the client in addition to the
/// parameters in the template.
/// @return requestId Request ID
function makeRequest(
bytes32 templateId,
uint256 requesterIndex,
address designatedWallet,
address fulfillAddress,
bytes4 fulfillFunctionId,
bytes calldata parameters
) external override returns (bytes32 requestId) {
require(
requesterIndexToClientAddressToEndorsementStatus[requesterIndex][msg.sender],
"Client not endorsed by requester"
);
uint256 clientNoRequests = clientAddressToNoRequests[msg.sender];
requestId = keccak256(abi.encode(clientNoRequests, block.chainid, msg.sender, templateId, parameters));
bytes32 airnodeId = templates[templateId].airnodeId;
requestIdToFulfillmentParameters[requestId] = keccak256(
abi.encodePacked(airnodeId, designatedWallet, fulfillAddress, fulfillFunctionId)
);
emit ClientRequestCreated(
airnodeId,
requestId,
clientNoRequests,
block.chainid,
msg.sender,
templateId,
requesterIndex,
designatedWallet,
fulfillAddress,
fulfillFunctionId,
parameters
);
clientAddressToNoRequests[msg.sender]++;
}
/// @notice Called by the client to make a full request. A full request
/// provides all of its parameters as arguments and does not refer to a
/// template.
/// @param airnodeId Airnode ID from AirnodeParameterStore
/// @param endpointId Endpoint ID from EndpointStore
/// @param requesterIndex Requester index from RequesterStore
/// @param designatedWallet Designated wallet that is requested to fulfill
/// the request
/// @param fulfillAddress Address that will be called to fulfill
/// @param fulfillFunctionId Signature of the function that will be called
/// to fulfill
/// @param parameters All request parameters
/// @return requestId Request ID
function makeFullRequest(
bytes32 airnodeId,
bytes32 endpointId,
uint256 requesterIndex,
address designatedWallet,
address fulfillAddress,
bytes4 fulfillFunctionId,
bytes calldata parameters
) external override returns (bytes32 requestId) {
require(
requesterIndexToClientAddressToEndorsementStatus[requesterIndex][msg.sender],
"Client not endorsed by requester"
);
uint256 clientNoRequests = clientAddressToNoRequests[msg.sender];
requestId = keccak256(abi.encode(clientNoRequests, block.chainid, msg.sender, endpointId, parameters));
requestIdToFulfillmentParameters[requestId] = keccak256(
abi.encodePacked(airnodeId, designatedWallet, fulfillAddress, fulfillFunctionId)
);
emit ClientFullRequestCreated(
airnodeId,
requestId,
clientNoRequests,
block.chainid,
msg.sender,
endpointId,
requesterIndex,
designatedWallet,
fulfillAddress,
fulfillFunctionId,
parameters
);
clientAddressToNoRequests[msg.sender]++;
}
/// @notice Called by Airnode to fulfill the request (regular or full)
/// @dev `statusCode` being zero indicates a successful fulfillment, while
/// non-zero values indicate error (the meanings of these values are
/// implementation-dependent).
/// The data is ABI-encoded as a `bytes` type, with its format depending on
/// the request specifications.
/// @param requestId Request ID
/// @param airnodeId Airnode ID from AirnodeParameterStore
/// @param statusCode Status code of the fulfillment
/// @param data Fulfillment data
/// @param fulfillAddress Address that will be called to fulfill
/// @param fulfillFunctionId Signature of the function that will be called
/// to fulfill
/// @return callSuccess If the fulfillment call succeeded
/// @return callData Data returned by the fulfillment call (if there is
/// any)
function fulfill(
bytes32 requestId,
bytes32 airnodeId,
uint256 statusCode,
bytes calldata data,
address fulfillAddress,
bytes4 fulfillFunctionId
)
external
override
onlyCorrectFulfillmentParameters(requestId, airnodeId, fulfillAddress, fulfillFunctionId)
returns (bool callSuccess, bytes memory callData)
{
delete requestIdToFulfillmentParameters[requestId];
emit ClientRequestFulfilled(airnodeId, requestId, statusCode, data);
(callSuccess, callData) = fulfillAddress.call( // solhint-disable-line
abi.encodeWithSelector(fulfillFunctionId, requestId, statusCode, data)
);
}
/// @notice Called by Airnode if the request cannot be fulfilled
/// @dev Airnode should fall back to this if a request cannot be fulfilled
/// because fulfill() reverts
/// @param requestId Request ID
/// @param airnodeId Airnode ID from AirnodeParameterStore
/// @param fulfillAddress Address that will be called to fulfill
/// @param fulfillFunctionId Signature of the function that will be called
/// to fulfill
function fail(
bytes32 requestId,
bytes32 airnodeId,
address fulfillAddress,
bytes4 fulfillFunctionId
) external override onlyCorrectFulfillmentParameters(requestId, airnodeId, fulfillAddress, fulfillFunctionId) {
delete requestIdToFulfillmentParameters[requestId];
// Failure is recorded so that it can be checked externally
requestWithIdHasFailed[requestId] = true;
emit ClientRequestFailed(airnodeId, requestId);
}
}
| 37,759 |
230 | // https:docs.synthetix.io/contracts/source/interfaces/irewardsdistribution | interface IRewardsDistribution {
// Structs
struct DistributionData {
address destination;
uint amount;
}
// Views
function authority() external view returns (address);
function distributions(uint index) external view returns (address destination, uint amount); // DistributionData
function distributionsLength() external view returns (uint);
// Mutative Functions
function distributeRewards(uint amount) external returns (bool);
}
| interface IRewardsDistribution {
// Structs
struct DistributionData {
address destination;
uint amount;
}
// Views
function authority() external view returns (address);
function distributions(uint index) external view returns (address destination, uint amount); // DistributionData
function distributionsLength() external view returns (uint);
// Mutative Functions
function distributeRewards(uint amount) external returns (bool);
}
| 31,271 |
19 | // function transfer(address _to, uint256 _value) publicreturns (bool success); function transferFrom(address _from, address _to, uint256 _value) publicreturns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); | function allowance(address _owner, address _spender) view external returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
| function allowance(address _owner, address _spender) view external returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
| 65,318 |
22 | // If trade gets 2 or more confirmation, release escrow buyer + seller, buyer + admin,seller & admin, or all of them | if (trades[tradeId].confirmations == 2){
uint tronBabaFee = trades[tradeId].tradeAmount.mul(babaFee).div(100);
baba.transfer(trades[tradeId].seller, trades[tradeId].tradeAmount.sub(tronBabaFee));
baba.transfer(tronBabaWallet, tronBabaFee);
trades[tradeId].released = true;
bool byAdmin = (msg.sender == trades[tradeId].admin);
emit TradeReleased(tradeId, trades[tradeId].seller, trades[tradeId].tradeAmount.sub(tronBabaFee), byAdmin);
}
| if (trades[tradeId].confirmations == 2){
uint tronBabaFee = trades[tradeId].tradeAmount.mul(babaFee).div(100);
baba.transfer(trades[tradeId].seller, trades[tradeId].tradeAmount.sub(tronBabaFee));
baba.transfer(tronBabaWallet, tronBabaFee);
trades[tradeId].released = true;
bool byAdmin = (msg.sender == trades[tradeId].admin);
emit TradeReleased(tradeId, trades[tradeId].seller, trades[tradeId].tradeAmount.sub(tronBabaFee), byAdmin);
}
| 53,152 |
463 | // The value that you would need to send so that the recipient receivesa specified value. value The value you want the recipient to receive / | function transferredAmountToReceive(uint value)
external
view
returns (uint)
| function transferredAmountToReceive(uint value)
external
view
returns (uint)
| 6,282 |
76 | // the address of the ENS registry | address ensRegistry;
| address ensRegistry;
| 309 |
109 | // transfer tokens to ppl accts (window1-5) _winNum - number of window 0-4 to close / | function sendTokensWindow(uint8 _winNum) onlyOwner stopInEmergency public {
| function sendTokensWindow(uint8 _winNum) onlyOwner stopInEmergency public {
| 33,567 |
98 | // Unbond liquidity for a pending keeper job / | function unbondJob() external {
liquidityUnbonding[msg.sender] = now.add(UNBOND);
emit UnbondJob(liquidityProvided[msg.sender], msg.sender, block.number, liquidityProviders[msg.sender]);
}
| function unbondJob() external {
liquidityUnbonding[msg.sender] = now.add(UNBOND);
emit UnbondJob(liquidityProvided[msg.sender], msg.sender, block.number, liquidityProviders[msg.sender]);
}
| 48,534 |
32 | // Enable TAX Mode | function enableTAXMode() public {
require (msg.sender == ownerWallet);
taxMode = true;
}
| function enableTAXMode() public {
require (msg.sender == ownerWallet);
taxMode = true;
}
| 20,785 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.