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 |
|---|---|---|---|---|
4 | // Withdraw ether from this contract (in case someone accidentally sends ETH to the contract) / | function withdraw() onlyOwner public payable {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
| function withdraw() onlyOwner public payable {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
| 36,967 |
291 | // Public sale minting | function mint(uint lootId) public payable nonReentrant {
require(!privateSale, "Public sale minting not started");
require(saleIsActive, "Sale must be active to mint");
require(publicPrice <= msg.value, "Ether value sent is not correct");
require(lootId > 0 && lootId < 8001, "Token ID invalid");
require(!_exists(lootId), "This token has already been minted");
_safeMint(msg.sender, lootId);
}
| function mint(uint lootId) public payable nonReentrant {
require(!privateSale, "Public sale minting not started");
require(saleIsActive, "Sale must be active to mint");
require(publicPrice <= msg.value, "Ether value sent is not correct");
require(lootId > 0 && lootId < 8001, "Token ID invalid");
require(!_exists(lootId), "This token has already been minted");
_safeMint(msg.sender, lootId);
}
| 18,681 |
8 | // 全局 Map 结构 | mapping(address => bool) userList;
mapping(address => bool) ownerList;
mapping(address => uint) public userType;
mapping(address => uint) public userAmount;
mapping(address => uint) public userReferrer;
uint256 public Type0;
uint256 public Type1;
uint256 public Type2;
| mapping(address => bool) userList;
mapping(address => bool) ownerList;
mapping(address => uint) public userType;
mapping(address => uint) public userAmount;
mapping(address => uint) public userReferrer;
uint256 public Type0;
uint256 public Type1;
uint256 public Type2;
| 24,115 |
1 | // Performs a foreign function call via terminal, (stringInputs) => (result) | function ffi(string[] calldata) external returns (bytes memory);
| function ffi(string[] calldata) external returns (bytes memory);
| 28,021 |
31 | // Sets initial values / | constructor(address token, address priceFeed, address adminWallet)
| constructor(address token, address priceFeed, address adminWallet)
| 39,237 |
53 | // Info of Pool Stage. | struct PoolStage {
uint256 amount;
uint256 buyVoteWeight;
uint256 buyAmount;
uint256 sellVoteWeight;
uint256 sellAmount;
uint256 claimAmount;
}
| struct PoolStage {
uint256 amount;
uint256 buyVoteWeight;
uint256 buyAmount;
uint256 sellVoteWeight;
uint256 sellAmount;
uint256 claimAmount;
}
| 32,832 |
93 | // Initializes the contract in unpaused state. / | constructor() {
_paused = false;
}
| constructor() {
_paused = false;
}
| 2,494 |
191 | // require(fraktionalized==false); require(IERC721(contractAddress).ownerOf(index) == address(this)); | IERC721(contractAddress).safeTransferFrom(address(this), msg.sender, index);
| IERC721(contractAddress).safeTransferFrom(address(this), msg.sender, index);
| 66,828 |
33 | // added override to 'IERC165' and 'interfaceId == type(IERC2981).interfaceId ||' to the return | function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerableUpgradeable, IERC165Upgradeable, IERC165)
returns (bool)
| function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerableUpgradeable, IERC165Upgradeable, IERC165)
returns (bool)
| 27,907 |
90 | // Both _hand and _draws store the first card in the rightmost position. _hand uses chunks of 6 bits. In the below example, hand is [9,18,35,12,32], and the cards 18 and 35 will be replaced. _hand:[9,18,35,12,32]encoding:XX 100000 001100 100011 010010 001001chunks: 32 12 35 189 order:card5, card4, card3, card2, card1 decimal:540161161 _draws: card2 and card4encoding: XXX00110 order:card5, card4, card3, card2, card1decimal:6Gas Cost: Fixed 6k gas. | function drawToHand(uint256 _hash, uint32 _hand, uint _draws)
public
pure
returns (uint32)
| function drawToHand(uint256 _hash, uint32 _hand, uint _draws)
public
pure
returns (uint32)
| 57,050 |
120 | // so the cast does not overflow | require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow');
return uq112x112(uint224(sum));
| require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow');
return uq112x112(uint224(sum));
| 11,518 |
4 | // The MVP Policy is a single step requiring a confirmation response / | function startAuthorization() external override {
senderRequires(Role.ADMIN);
validatePolicyInitialized();
uint64 pendingActionId = _actions.createPending(_policyId);
validateActionId(pendingActionId);
uint sentChallengeCount = 0;
for(uint i=0; i < _approverAgentIds.length; i++){
sentChallengeCount += createChallengesForDevices(pendingActionId, _approverAgentIds[i]);
}
if(sentChallengeCount < _approvalsRequired){
revert("Insufficient Challenges sent to satisfy approval criteria");
}
}
| function startAuthorization() external override {
senderRequires(Role.ADMIN);
validatePolicyInitialized();
uint64 pendingActionId = _actions.createPending(_policyId);
validateActionId(pendingActionId);
uint sentChallengeCount = 0;
for(uint i=0; i < _approverAgentIds.length; i++){
sentChallengeCount += createChallengesForDevices(pendingActionId, _approverAgentIds[i]);
}
if(sentChallengeCount < _approvalsRequired){
revert("Insufficient Challenges sent to satisfy approval criteria");
}
}
| 44,957 |
13 | // allow contract to recieve funds / | event Received(address, uint);
| event Received(address, uint);
| 11,828 |
28 | // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. spender The address which will spend the funds. value The amount of tokens to be spent. / | function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
| function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
| 1,576 |
16 | // divide this number by 32 (to get from bit offsets to actual number) | uint playerNonceMod8 = betOffsetInSlot >> MULTIPLY_BY_32_BIT_SHIFT;
| uint playerNonceMod8 = betOffsetInSlot >> MULTIPLY_BY_32_BIT_SHIFT;
| 2,157 |
18 | // returns nonce / | function nonce() public view returns (uint256) {
return nonce_;
}
| function nonce() public view returns (uint256) {
return nonce_;
}
| 49,440 |
50 | // Test all token addresses at once | require(
TokenRegistry(tokenRegistryAddress).areAllTokensRegistered(tokens)
); // "token not registered");
| require(
TokenRegistry(tokenRegistryAddress).areAllTokensRegistered(tokens)
); // "token not registered");
| 45,016 |
266 | // Ensure payment token allowance to the TransferProxy Note that the paymentToken may also be used as a component to issue the Set So the paymentTokenQuantity must be used vs. the exchangeIssuanceParams sendToken quantity | ERC20Wrapper.ensureAllowance(
_paymentTokenAddress,
address(this),
address(transferProxyInstance),
_paymentTokenQuantity
);
| ERC20Wrapper.ensureAllowance(
_paymentTokenAddress,
address(this),
address(transferProxyInstance),
_paymentTokenQuantity
);
| 19,845 |
43 | // mint staking shares at current rate | uint256 mintedStakingShares = (totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(INITIAL_SHARES_PER_TOKEN);
require(mintedStakingShares > 0, "Geyser: stake amount too small");
| uint256 mintedStakingShares = (totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(INITIAL_SHARES_PER_TOKEN);
require(mintedStakingShares > 0, "Geyser: stake amount too small");
| 46,779 |
12 | // 轉帳 | function transfer(address to, uint256 etherValue) public {
uint256 weiValue = etherValue * 1 ether;
require(balance[msg.sender] >= weiValue, "your balances are not enough");
balance[msg.sender] -= weiValue;
balance[to] += weiValue;
// emit TransferEvent
emit TransferEvent(msg.sender, to, etherValue, block.timestamp);
}
| function transfer(address to, uint256 etherValue) public {
uint256 weiValue = etherValue * 1 ether;
require(balance[msg.sender] >= weiValue, "your balances are not enough");
balance[msg.sender] -= weiValue;
balance[to] += weiValue;
// emit TransferEvent
emit TransferEvent(msg.sender, to, etherValue, block.timestamp);
}
| 51,973 |
116 | // Pause or unpause the contract / | function pause() external onlyOwner {
paused = !paused;
}
| function pause() external onlyOwner {
paused = !paused;
}
| 23,883 |
121 | // caller | function bond() external payable;
function startUnbond() external;
function cancelUnbond() external;
function unbondAll() external;
function unbond(uint256 _amount) external;
| function bond() external payable;
function startUnbond() external;
function cancelUnbond() external;
function unbondAll() external;
function unbond(uint256 _amount) external;
| 56,996 |
57 | // True if the proposal should be accepted. | bool suportProposal;
| bool suportProposal;
| 52,130 |
95 | // Returns true if a 'leaf' can be proved to be a part of a Merkle tree defined by 'root'. For this, a 'proof' must be provided, containing sibling hashes on the branch from the leaf to the root of the tree. Each pair of leaves and each pair of pre-images are assumed to be sorted./ | function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
| function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
| 4,622 |
163 | // INTERNAL FUNCTIONS // Token Transfers // Transfer tokens from a specific partition. _fromPartition Partition of the tokens to transfer. _operator The address performing the transfer. _from Token holder. _to Token recipient. _value Number of tokens to transfer. _data Information attached to the transfer. Contains the destinationpartition if a partition change is requested. _operatorData Information attached to the transfer, by the operator(if any).return Destination partition. / | function _transferByPartition(
bytes32 _fromPartition,
address _operator,
address _from,
address _to,
uint256 _value,
bytes memory _data,
bytes memory _operatorData
| function _transferByPartition(
bytes32 _fromPartition,
address _operator,
address _from,
address _to,
uint256 _value,
bytes memory _data,
bytes memory _operatorData
| 27,279 |
27 | // has to be reset even though we don't use it in the single hop case | amountInCached = DEFAULT_AMOUNT_IN_CACHED;
| amountInCached = DEFAULT_AMOUNT_IN_CACHED;
| 31,458 |
1 | // Indicator that this is an InterestRateModel contract (for inspection) | bool public constant isInterestRateModel = true;
| bool public constant isInterestRateModel = true;
| 27,275 |
21 | // Throws if called through proxy by any account other than contract itself or an upgradeability owner. / | modifier onlyRelevantSender() {
(bool isProxy, bytes memory returnData) = address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER));
require(
!isProxy || // covers usage without calling through storage proxy
(returnData.length == 32 && msg.sender == abi.decode(returnData, (address))) || // covers usage through regular proxy calls
msg.sender == address(this) // covers calls through upgradeAndCall proxy method
);
_;
}
| modifier onlyRelevantSender() {
(bool isProxy, bytes memory returnData) = address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER));
require(
!isProxy || // covers usage without calling through storage proxy
(returnData.length == 32 && msg.sender == abi.decode(returnData, (address))) || // covers usage through regular proxy calls
msg.sender == address(this) // covers calls through upgradeAndCall proxy method
);
_;
}
| 39,037 |
72 | // Optional token name | bytes32 public name = "";
| bytes32 public name = "";
| 25,545 |
431 | // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. | disputedLiquidation.state = Status.PendingDispute;
disputedLiquidation.disputer = msg.sender;
| disputedLiquidation.state = Status.PendingDispute;
disputedLiquidation.disputer = msg.sender;
| 30,881 |
103 | // Set apwibt address _apwibt the address of the new apwibt used only for exceptional purpose / | function setAPWIBT(address _apwibt) external;
| function setAPWIBT(address _apwibt) external;
| 23,646 |
39 | // User Accounting | uint256 newUserSeconds =
now
.sub(totals.lastTimestampSec)
.mul(totals.stakingShares);
totals.stakingShareSeconds =
totals.stakingShareSeconds
.add(newUserSeconds);
uint256 totalUserRewards = (globalSeconds > 0)
? UnlockedTokens.mul(totals.stakingShareSeconds).div(globalSeconds)
: 0;
| uint256 newUserSeconds =
now
.sub(totals.lastTimestampSec)
.mul(totals.stakingShares);
totals.stakingShareSeconds =
totals.stakingShareSeconds
.add(newUserSeconds);
uint256 totalUserRewards = (globalSeconds > 0)
? UnlockedTokens.mul(totals.stakingShareSeconds).div(globalSeconds)
: 0;
| 2,538 |
50 | // perform a multi-path distributed swap | function multiPathSwap(
SwapParams memory _swap,
Token[] calldata _path,
DistributionParams[] memory _distribution
| function multiPathSwap(
SwapParams memory _swap,
Token[] calldata _path,
DistributionParams[] memory _distribution
| 30,137 |
13 | // Staking function which updates the user balances in the parent contract / | function stake(uint256 amount) public override {
require(amount > 0, "Cannot stake 0");
updateReward(msg.sender);
// Call the parent to adjust the balances.
super.stake(amount);
// Adjust the bonus effective stake according to the multiplier.
uint256 boostedBalance = deflector.calculateBoostedBalance(msg.sender, _balances[msg.sender].balance);
adjustBoostedBalance(boostedBalance);
emit Staked(msg.sender, amount);
}
| function stake(uint256 amount) public override {
require(amount > 0, "Cannot stake 0");
updateReward(msg.sender);
// Call the parent to adjust the balances.
super.stake(amount);
// Adjust the bonus effective stake according to the multiplier.
uint256 boostedBalance = deflector.calculateBoostedBalance(msg.sender, _balances[msg.sender].balance);
adjustBoostedBalance(boostedBalance);
emit Staked(msg.sender, amount);
}
| 43,154 |
241 | // The length of the time window where a rebase operation is allowed to execute, in seconds. |
uint256 public rebaseWindowLengthSec;
|
uint256 public rebaseWindowLengthSec;
| 2,979 |
38 | // Composite plus token. A composite plus token is backed by a basket of plus token. The composite plus token,along with its underlying tokens in the basket, should have the same peg. / | contract CompositePlus is ICompositePlus, Plus, ReentrancyGuardUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeMathUpgradeable for uint256;
event Minted(address indexed user, address[] tokens, uint256[] amounts, uint256 mintShare, uint256 mintAmount);
event Redeemed(address indexed user, address[] tokens, uint256[] amounts, uint256 redeemShare, uint256 redeemAmount, uint256 fee);
event RebalancerUpdated(address indexed rebalancer, bool enabled);
event MinLiquidityRatioUpdated(uint256 oldRatio, uint256 newRatio);
event TokenAdded(address indexed token);
event TokenRemoved(address indexed token);
event Rebalanced(uint256 underlyingBefore, uint256 underlyingAfter, uint256 supply);
// The underlying plus tokens that constitutes the composite plus token.
address[] public override tokens;
// Mapping: Token address => Whether the token is an underlying token.
mapping(address => bool) public override tokenSupported;
// Mapping: Token address => Whether minting with token is paused
mapping(address => bool) public mintPaused;
// Mapping: Address => Whether this is a rebalancer contract.
mapping(address => bool) public rebalancers;
// Liquidity ratio = Total supply / Total underlying
// Liquidity ratio should larger than 1 in most cases except a short period after rebalance.
// Minimum liquidity ratio sets the upper bound of impermanent loss caused by rebalance.
uint256 public minLiquidityRatio;
/**
* @dev Initlaizes the composite plus token.
*/
function initialize(string memory _name, string memory _symbol) public initializer {
__PlusToken__init(_name, _symbol);
__ReentrancyGuard_init();
}
/**
* @dev Returns the total value of the plus token in terms of the peg value.
* All underlying token amounts have been scaled to 18 decimals and expressed in WAD.
*/
function _totalUnderlyingInWad() internal view virtual override returns (uint256) {
uint256 _amount = 0;
for (uint256 i = 0; i < tokens.length; i++) {
// Since all underlying tokens in the baskets are plus tokens with the same value peg, the amount
// minted is the amount of all plus tokens in the basket added.
// Note: All plus tokens, single or composite, have 18 decimals.
_amount = _amount.add(IERC20Upgradeable(tokens[i]).balanceOf(address(this)));
}
// Plus tokens are in 18 decimals, need to return in WAD.
return _amount.mul(WAD);
}
/**
* @dev Returns the amount of composite plus tokens minted with the tokens provided.
* @dev _tokens The tokens used to mint the composite plus token.
* @dev _amounts Amount of tokens used to mint the composite plus token.
*/
function getMintAmount(address[] calldata _tokens, uint256[] calldata _amounts) external view returns(uint256) {
require(_tokens.length == _amounts.length, "invalid input");
uint256 _amount = 0;
for (uint256 i = 0; i < _tokens.length; i++) {
require(!mintPaused[_tokens[i]], "token paused");
require(tokenSupported[_tokens[i]], "token not supported");
if (_amounts[i] == 0) continue;
// Since all underlying tokens in the baskets are plus tokens with the same value peg, the amount
// minted is the amount of all tokens to mint added.
// Note: All plus tokens, single or composite, have 18 decimals.
_amount = _amount.add(_amounts[i]);
}
return _amount;
}
/**
* @dev Mints composite plus tokens with underlying tokens provided.
* @dev _tokens The tokens used to mint the composite plus token. The composite plus token must have sufficient allownance on the token.
* @dev _amounts Amount of tokens used to mint the composite plus token.
*/
function mint(address[] calldata _tokens, uint256[] calldata _amounts) external override nonReentrant {
require(_tokens.length == _amounts.length, "invalid input");
// Rebase first to make index up-to-date
rebase();
uint256 _amount = 0;
for (uint256 i = 0; i < _tokens.length; i++) {
require(tokenSupported[_tokens[i]], "token not supported");
require(!mintPaused[_tokens[i]], "token paused");
if (_amounts[i] == 0) continue;
_amount = _amount.add(_amounts[i]);
// Transfers the token into pool.
IERC20Upgradeable(_tokens[i]).safeTransferFrom(msg.sender, address(this), _amounts[i]);
}
uint256 _share = _amount.mul(WAD).div(index);
uint256 _oldShare = userShare[msg.sender];
uint256 _newShare = _oldShare.add(_share);
uint256 _totalShares = totalShares.add(_share);
totalShares = _totalShares;
userShare[msg.sender] = _newShare;
emit UserShareUpdated(msg.sender, _oldShare, _newShare, _totalShares);
emit Minted(msg.sender, _tokens, _amounts, _share, _amount);
}
/**
* @dev Returns the amount of tokens received in redeeming the composite plus token.
* @param _amount Amounf of composite plus to redeem.
* @return Addresses and amounts of tokens returned as well as fee collected.
*/
function getRedeemAmount(uint256 _amount) external view returns (address[] memory, uint256[] memory, uint256, uint256) {
require(_amount > 0, "zero amount");
// Special handling of -1 is required here in order to fully redeem all shares, since interest
// will be accrued between the redeem transaction is signed and mined.
uint256 _share;
if (_amount == uint256(int256(-1))) {
_share = userShare[msg.sender];
_amount = _share.mul(index).div(WAD);
} else {
_share = _amount.mul(WAD).div(index);
}
// Withdraw ratio = min(liquidity ratio, 1 - redeem fee)
// Liquidity ratio is in WAD and redeem fee is in 0.01%
uint256 _withdrawAmount1 = _amount.mul(liquidityRatio()).div(WAD);
uint256 _withdrawAmount2 = _amount.mul(MAX_PERCENT - redeemFee).div(MAX_PERCENT);
uint256 _withdrawAmount = MathUpgradeable.min(_withdrawAmount1, _withdrawAmount2);
uint256 _fee = _amount.sub(_withdrawAmount);
address[] memory _redeemTokens = tokens;
uint256[] memory _redeemAmounts = new uint256[](_redeemTokens.length);
uint256 _totalSupply = totalSupply();
for (uint256 i = 0; i < _redeemTokens.length; i++) {
uint256 _balance = IERC20Upgradeable(_redeemTokens[i]).balanceOf(address(this));
if (_balance == 0) continue;
_redeemAmounts[i] = _balance.mul(_withdrawAmount).div(_totalSupply);
}
return (_redeemTokens, _redeemAmounts, _share, _fee);
}
/**
* @dev Redeems the composite plus token. In the current implementation only proportional redeem is supported.
* @param _amount Amount of composite plus token to redeem. -1 means redeeming all shares.
*/
function redeem(uint256 _amount) external override nonReentrant {
require(_amount > 0, "zero amount");
// Rebase first to make index up-to-date
rebase();
// Special handling of -1 is required here in order to fully redeem all shares, since interest
// will be accrued between the redeem transaction is signed and mined.
uint256 _share;
if (_amount == uint256(int256(-1))) {
_share = userShare[msg.sender];
_amount = _share.mul(index).div(WAD);
} else {
_share = _amount.mul(WAD).div(index);
}
// Withdraw ratio = min(liquidity ratio, 1 - redeem fee)
uint256 _withdrawAmount1 = _amount.mul(liquidityRatio()).div(WAD);
uint256 _withdrawAmount2 = _amount.mul(MAX_PERCENT - redeemFee).div(MAX_PERCENT);
uint256 _withdrawAmount = MathUpgradeable.min(_withdrawAmount1, _withdrawAmount2);
uint256 _fee = _amount.sub(_withdrawAmount);
address[] memory _redeemTokens = tokens;
uint256[] memory _redeemAmounts = new uint256[](_redeemTokens.length);
uint256 _totalSupply = totalSupply();
for (uint256 i = 0; i < _redeemTokens.length; i++) {
uint256 _balance = IERC20Upgradeable(_redeemTokens[i]).balanceOf(address(this));
if (_balance == 0) continue;
_redeemAmounts[i] = _balance.mul(_withdrawAmount).div(_totalSupply);
IERC20Upgradeable(_redeemTokens[i]).safeTransfer(msg.sender, _redeemAmounts[i]);
}
// Updates the balance
uint256 _oldShare = userShare[msg.sender];
uint256 _newShare = _oldShare.sub(_share);
totalShares = totalShares.sub(_share);
userShare[msg.sender] = _newShare;
emit UserShareUpdated(msg.sender, _oldShare, _newShare, totalShares);
emit Redeemed(msg.sender, _redeemTokens, _redeemAmounts, _share, _amount, _fee);
}
/**
* @dev Updates the mint paused state of a token.
* @param _token Token to update mint paused.
* @param _paused Whether minting with that token is paused.
*/
function setMintPaused(address _token, bool _paused) external onlyStrategist {
require(tokenSupported[_token], "not supported");
require(mintPaused[_token] != _paused, "no change");
mintPaused[_token] = _paused;
emit MintPausedUpdated(_token, _paused);
}
/**
* @dev Adds a new rebalancer. Only governance can add new rebalancers.
*/
function addRebalancer(address _rebalancer) external onlyGovernance {
require(_rebalancer != address(0x0), "rebalancer not set");
require(!rebalancers[_rebalancer], "rebalancer exist");
rebalancers[_rebalancer] = true;
emit RebalancerUpdated(_rebalancer, true);
}
/**
* @dev Remove an existing rebalancer. Only strategist can remove existing rebalancers.
*/
function removeRebalancer(address _rebalancer) external onlyStrategist {
require(rebalancers[_rebalancer], "rebalancer exist");
rebalancers[_rebalancer] = false;
emit RebalancerUpdated(_rebalancer, false);
}
/**
* @dev Udpates the minimum liquidity ratio. Only governance can update minimum liquidity ratio.
*/
function setMinLiquidityRatio(uint256 _minLiquidityRatio) external onlyGovernance {
require(_minLiquidityRatio <= WAD, "overflow");
require(_minLiquidityRatio <= liquidityRatio(), "ratio too big");
uint256 _oldRatio = minLiquidityRatio;
minLiquidityRatio = _minLiquidityRatio;
emit MinLiquidityRatioUpdated(_oldRatio, _minLiquidityRatio);
}
/**
* @dev Adds a new plus token to the basket. Only governance can add new plus token.
* @param _token The new plus token to add.
*/
function addToken(address _token) external onlyGovernance {
require(_token != address(0x0), "token not set");
require(!tokenSupported[_token], "token exists");
tokenSupported[_token] = true;
tokens.push(_token);
emit TokenAdded(_token);
}
/**
* @dev Removes a plus token from the basket. Only governance can remove a plus token.
* Note: A token cannot be removed if it's balance is not zero!
* @param _token The plus token to remove from the basket.
*/
function removeToken(address _token) external onlyGovernance {
require(tokenSupported[_token], "token not exists");
require(IERC20Upgradeable(_token).balanceOf(address(this)) == 0, "nonzero balance");
uint256 _tokenSize = tokens.length;
uint256 _tokenIndex = _tokenSize;
for (uint256 i = 0; i < _tokenSize; i++) {
if (tokens[i] == _token) {
_tokenIndex = i;
break;
}
}
// We must have found the token!
assert(_tokenIndex < _tokenSize);
tokens[_tokenIndex] = tokens[_tokenSize - 1];
tokens.pop();
delete tokenSupported[_token];
// Delete the mint paused state as well
delete mintPaused[_token];
emit TokenRemoved(_token);
}
/**
* @dev Return the total number of tokens.
*/
function tokenSize() external view returns (uint256) {
return tokens.length;
}
/**
* @dev Rebalances the basket, e.g. for a better yield. Only strategist can perform rebalance.
* @param _tokens Address of the tokens to withdraw from the basket.
* @param _amounts Amounts of the tokens to withdraw from the basket.
* @param _rebalancer Address of the rebalancer contract to invoke.
* @param _data Data to invoke on rebalancer contract.
*/
function rebalance(address[] memory _tokens, uint256[] memory _amounts, address _rebalancer, bytes calldata _data) external onlyStrategist {
require(rebalancers[_rebalancer], "invalid rebalancer");
require(_tokens.length == _amounts.length, "invalid input");
// Rebase first to make index up-to-date
rebase();
uint256 _underlyingBefore = _totalUnderlyingInWad();
for (uint256 i = 0; i < _tokens.length; i++) {
require(tokenSupported[_tokens[i]], "token not supported");
if (_amounts[i] == 0) continue;
IERC20Upgradeable(_tokens[i]).safeTransfer(_rebalancer, _amounts[i]);
}
// Invokes rebalancer contract.
IRebalancer(_rebalancer).rebalance(_tokens, _amounts, _data);
// Check post-rebalance conditions.
uint256 _underlyingAfter = _totalUnderlyingInWad();
uint256 _supply = totalSupply();
// _underlyingAfter / _supply > minLiquidityRatio
require(_underlyingAfter > _supply.mul(minLiquidityRatio), "too much loss");
emit Rebalanced(_underlyingBefore, _underlyingAfter, _supply);
}
/**
* @dev Checks whether a token can be salvaged via salvageToken().
* @param _token Token to check salvageability.
*/
function _salvageable(address _token) internal view override returns (bool) {
// For composite plus, all tokens in the basekt cannot be salvaged!
return !tokenSupported[_token];
}
uint256[50] private __gap;
}
| contract CompositePlus is ICompositePlus, Plus, ReentrancyGuardUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeMathUpgradeable for uint256;
event Minted(address indexed user, address[] tokens, uint256[] amounts, uint256 mintShare, uint256 mintAmount);
event Redeemed(address indexed user, address[] tokens, uint256[] amounts, uint256 redeemShare, uint256 redeemAmount, uint256 fee);
event RebalancerUpdated(address indexed rebalancer, bool enabled);
event MinLiquidityRatioUpdated(uint256 oldRatio, uint256 newRatio);
event TokenAdded(address indexed token);
event TokenRemoved(address indexed token);
event Rebalanced(uint256 underlyingBefore, uint256 underlyingAfter, uint256 supply);
// The underlying plus tokens that constitutes the composite plus token.
address[] public override tokens;
// Mapping: Token address => Whether the token is an underlying token.
mapping(address => bool) public override tokenSupported;
// Mapping: Token address => Whether minting with token is paused
mapping(address => bool) public mintPaused;
// Mapping: Address => Whether this is a rebalancer contract.
mapping(address => bool) public rebalancers;
// Liquidity ratio = Total supply / Total underlying
// Liquidity ratio should larger than 1 in most cases except a short period after rebalance.
// Minimum liquidity ratio sets the upper bound of impermanent loss caused by rebalance.
uint256 public minLiquidityRatio;
/**
* @dev Initlaizes the composite plus token.
*/
function initialize(string memory _name, string memory _symbol) public initializer {
__PlusToken__init(_name, _symbol);
__ReentrancyGuard_init();
}
/**
* @dev Returns the total value of the plus token in terms of the peg value.
* All underlying token amounts have been scaled to 18 decimals and expressed in WAD.
*/
function _totalUnderlyingInWad() internal view virtual override returns (uint256) {
uint256 _amount = 0;
for (uint256 i = 0; i < tokens.length; i++) {
// Since all underlying tokens in the baskets are plus tokens with the same value peg, the amount
// minted is the amount of all plus tokens in the basket added.
// Note: All plus tokens, single or composite, have 18 decimals.
_amount = _amount.add(IERC20Upgradeable(tokens[i]).balanceOf(address(this)));
}
// Plus tokens are in 18 decimals, need to return in WAD.
return _amount.mul(WAD);
}
/**
* @dev Returns the amount of composite plus tokens minted with the tokens provided.
* @dev _tokens The tokens used to mint the composite plus token.
* @dev _amounts Amount of tokens used to mint the composite plus token.
*/
function getMintAmount(address[] calldata _tokens, uint256[] calldata _amounts) external view returns(uint256) {
require(_tokens.length == _amounts.length, "invalid input");
uint256 _amount = 0;
for (uint256 i = 0; i < _tokens.length; i++) {
require(!mintPaused[_tokens[i]], "token paused");
require(tokenSupported[_tokens[i]], "token not supported");
if (_amounts[i] == 0) continue;
// Since all underlying tokens in the baskets are plus tokens with the same value peg, the amount
// minted is the amount of all tokens to mint added.
// Note: All plus tokens, single or composite, have 18 decimals.
_amount = _amount.add(_amounts[i]);
}
return _amount;
}
/**
* @dev Mints composite plus tokens with underlying tokens provided.
* @dev _tokens The tokens used to mint the composite plus token. The composite plus token must have sufficient allownance on the token.
* @dev _amounts Amount of tokens used to mint the composite plus token.
*/
function mint(address[] calldata _tokens, uint256[] calldata _amounts) external override nonReentrant {
require(_tokens.length == _amounts.length, "invalid input");
// Rebase first to make index up-to-date
rebase();
uint256 _amount = 0;
for (uint256 i = 0; i < _tokens.length; i++) {
require(tokenSupported[_tokens[i]], "token not supported");
require(!mintPaused[_tokens[i]], "token paused");
if (_amounts[i] == 0) continue;
_amount = _amount.add(_amounts[i]);
// Transfers the token into pool.
IERC20Upgradeable(_tokens[i]).safeTransferFrom(msg.sender, address(this), _amounts[i]);
}
uint256 _share = _amount.mul(WAD).div(index);
uint256 _oldShare = userShare[msg.sender];
uint256 _newShare = _oldShare.add(_share);
uint256 _totalShares = totalShares.add(_share);
totalShares = _totalShares;
userShare[msg.sender] = _newShare;
emit UserShareUpdated(msg.sender, _oldShare, _newShare, _totalShares);
emit Minted(msg.sender, _tokens, _amounts, _share, _amount);
}
/**
* @dev Returns the amount of tokens received in redeeming the composite plus token.
* @param _amount Amounf of composite plus to redeem.
* @return Addresses and amounts of tokens returned as well as fee collected.
*/
function getRedeemAmount(uint256 _amount) external view returns (address[] memory, uint256[] memory, uint256, uint256) {
require(_amount > 0, "zero amount");
// Special handling of -1 is required here in order to fully redeem all shares, since interest
// will be accrued between the redeem transaction is signed and mined.
uint256 _share;
if (_amount == uint256(int256(-1))) {
_share = userShare[msg.sender];
_amount = _share.mul(index).div(WAD);
} else {
_share = _amount.mul(WAD).div(index);
}
// Withdraw ratio = min(liquidity ratio, 1 - redeem fee)
// Liquidity ratio is in WAD and redeem fee is in 0.01%
uint256 _withdrawAmount1 = _amount.mul(liquidityRatio()).div(WAD);
uint256 _withdrawAmount2 = _amount.mul(MAX_PERCENT - redeemFee).div(MAX_PERCENT);
uint256 _withdrawAmount = MathUpgradeable.min(_withdrawAmount1, _withdrawAmount2);
uint256 _fee = _amount.sub(_withdrawAmount);
address[] memory _redeemTokens = tokens;
uint256[] memory _redeemAmounts = new uint256[](_redeemTokens.length);
uint256 _totalSupply = totalSupply();
for (uint256 i = 0; i < _redeemTokens.length; i++) {
uint256 _balance = IERC20Upgradeable(_redeemTokens[i]).balanceOf(address(this));
if (_balance == 0) continue;
_redeemAmounts[i] = _balance.mul(_withdrawAmount).div(_totalSupply);
}
return (_redeemTokens, _redeemAmounts, _share, _fee);
}
/**
* @dev Redeems the composite plus token. In the current implementation only proportional redeem is supported.
* @param _amount Amount of composite plus token to redeem. -1 means redeeming all shares.
*/
function redeem(uint256 _amount) external override nonReentrant {
require(_amount > 0, "zero amount");
// Rebase first to make index up-to-date
rebase();
// Special handling of -1 is required here in order to fully redeem all shares, since interest
// will be accrued between the redeem transaction is signed and mined.
uint256 _share;
if (_amount == uint256(int256(-1))) {
_share = userShare[msg.sender];
_amount = _share.mul(index).div(WAD);
} else {
_share = _amount.mul(WAD).div(index);
}
// Withdraw ratio = min(liquidity ratio, 1 - redeem fee)
uint256 _withdrawAmount1 = _amount.mul(liquidityRatio()).div(WAD);
uint256 _withdrawAmount2 = _amount.mul(MAX_PERCENT - redeemFee).div(MAX_PERCENT);
uint256 _withdrawAmount = MathUpgradeable.min(_withdrawAmount1, _withdrawAmount2);
uint256 _fee = _amount.sub(_withdrawAmount);
address[] memory _redeemTokens = tokens;
uint256[] memory _redeemAmounts = new uint256[](_redeemTokens.length);
uint256 _totalSupply = totalSupply();
for (uint256 i = 0; i < _redeemTokens.length; i++) {
uint256 _balance = IERC20Upgradeable(_redeemTokens[i]).balanceOf(address(this));
if (_balance == 0) continue;
_redeemAmounts[i] = _balance.mul(_withdrawAmount).div(_totalSupply);
IERC20Upgradeable(_redeemTokens[i]).safeTransfer(msg.sender, _redeemAmounts[i]);
}
// Updates the balance
uint256 _oldShare = userShare[msg.sender];
uint256 _newShare = _oldShare.sub(_share);
totalShares = totalShares.sub(_share);
userShare[msg.sender] = _newShare;
emit UserShareUpdated(msg.sender, _oldShare, _newShare, totalShares);
emit Redeemed(msg.sender, _redeemTokens, _redeemAmounts, _share, _amount, _fee);
}
/**
* @dev Updates the mint paused state of a token.
* @param _token Token to update mint paused.
* @param _paused Whether minting with that token is paused.
*/
function setMintPaused(address _token, bool _paused) external onlyStrategist {
require(tokenSupported[_token], "not supported");
require(mintPaused[_token] != _paused, "no change");
mintPaused[_token] = _paused;
emit MintPausedUpdated(_token, _paused);
}
/**
* @dev Adds a new rebalancer. Only governance can add new rebalancers.
*/
function addRebalancer(address _rebalancer) external onlyGovernance {
require(_rebalancer != address(0x0), "rebalancer not set");
require(!rebalancers[_rebalancer], "rebalancer exist");
rebalancers[_rebalancer] = true;
emit RebalancerUpdated(_rebalancer, true);
}
/**
* @dev Remove an existing rebalancer. Only strategist can remove existing rebalancers.
*/
function removeRebalancer(address _rebalancer) external onlyStrategist {
require(rebalancers[_rebalancer], "rebalancer exist");
rebalancers[_rebalancer] = false;
emit RebalancerUpdated(_rebalancer, false);
}
/**
* @dev Udpates the minimum liquidity ratio. Only governance can update minimum liquidity ratio.
*/
function setMinLiquidityRatio(uint256 _minLiquidityRatio) external onlyGovernance {
require(_minLiquidityRatio <= WAD, "overflow");
require(_minLiquidityRatio <= liquidityRatio(), "ratio too big");
uint256 _oldRatio = minLiquidityRatio;
minLiquidityRatio = _minLiquidityRatio;
emit MinLiquidityRatioUpdated(_oldRatio, _minLiquidityRatio);
}
/**
* @dev Adds a new plus token to the basket. Only governance can add new plus token.
* @param _token The new plus token to add.
*/
function addToken(address _token) external onlyGovernance {
require(_token != address(0x0), "token not set");
require(!tokenSupported[_token], "token exists");
tokenSupported[_token] = true;
tokens.push(_token);
emit TokenAdded(_token);
}
/**
* @dev Removes a plus token from the basket. Only governance can remove a plus token.
* Note: A token cannot be removed if it's balance is not zero!
* @param _token The plus token to remove from the basket.
*/
function removeToken(address _token) external onlyGovernance {
require(tokenSupported[_token], "token not exists");
require(IERC20Upgradeable(_token).balanceOf(address(this)) == 0, "nonzero balance");
uint256 _tokenSize = tokens.length;
uint256 _tokenIndex = _tokenSize;
for (uint256 i = 0; i < _tokenSize; i++) {
if (tokens[i] == _token) {
_tokenIndex = i;
break;
}
}
// We must have found the token!
assert(_tokenIndex < _tokenSize);
tokens[_tokenIndex] = tokens[_tokenSize - 1];
tokens.pop();
delete tokenSupported[_token];
// Delete the mint paused state as well
delete mintPaused[_token];
emit TokenRemoved(_token);
}
/**
* @dev Return the total number of tokens.
*/
function tokenSize() external view returns (uint256) {
return tokens.length;
}
/**
* @dev Rebalances the basket, e.g. for a better yield. Only strategist can perform rebalance.
* @param _tokens Address of the tokens to withdraw from the basket.
* @param _amounts Amounts of the tokens to withdraw from the basket.
* @param _rebalancer Address of the rebalancer contract to invoke.
* @param _data Data to invoke on rebalancer contract.
*/
function rebalance(address[] memory _tokens, uint256[] memory _amounts, address _rebalancer, bytes calldata _data) external onlyStrategist {
require(rebalancers[_rebalancer], "invalid rebalancer");
require(_tokens.length == _amounts.length, "invalid input");
// Rebase first to make index up-to-date
rebase();
uint256 _underlyingBefore = _totalUnderlyingInWad();
for (uint256 i = 0; i < _tokens.length; i++) {
require(tokenSupported[_tokens[i]], "token not supported");
if (_amounts[i] == 0) continue;
IERC20Upgradeable(_tokens[i]).safeTransfer(_rebalancer, _amounts[i]);
}
// Invokes rebalancer contract.
IRebalancer(_rebalancer).rebalance(_tokens, _amounts, _data);
// Check post-rebalance conditions.
uint256 _underlyingAfter = _totalUnderlyingInWad();
uint256 _supply = totalSupply();
// _underlyingAfter / _supply > minLiquidityRatio
require(_underlyingAfter > _supply.mul(minLiquidityRatio), "too much loss");
emit Rebalanced(_underlyingBefore, _underlyingAfter, _supply);
}
/**
* @dev Checks whether a token can be salvaged via salvageToken().
* @param _token Token to check salvageability.
*/
function _salvageable(address _token) internal view override returns (bool) {
// For composite plus, all tokens in the basekt cannot be salvaged!
return !tokenSupported[_token];
}
uint256[50] private __gap;
}
| 16,981 |
6 | // length-prepend the relaySignal bytearray | signal = abi.encodePacked(uint16(message.relaySignal.length), message.relaySignal);
| signal = abi.encodePacked(uint16(message.relaySignal.length), message.relaySignal);
| 23,547 |
58 | // Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. _beneficiary Address performing the token purchase _tokenAmount Number of tokens to be emitted / | function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
| function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
| 11,045 |
283 | // This limit is necessary for onchain randomness | uint256 public constant MAX_SUPPLY_LIMIT = 10**9;
| uint256 public constant MAX_SUPPLY_LIMIT = 10**9;
| 19,186 |
1 | // 核酸检测信息表, key : account, field : asset_value |身份证号(主键) | 姓名|检测结果| 检测时间| |-------------------- |-------------------|------------------- |-------------------| |id | name|result| date| |---------------------|-------------------|------------------- |-------------------| 创建表 | tf.createTable("t_hospital", "id", "name,result,date");
| tf.createTable("t_hospital", "id", "name,result,date");
| 46,184 |
164 | // File: hasTransactionCap.sol | abstract contract hasTransactionCap is Ownable {
mapping (uint256 => uint256) transactionCap;
function getTransactionCapForToken(uint256 _id) public view returns(uint256) {
return transactionCap[_id];
}
function setTransactionCapForToken(uint256 _id, uint256 _transactionCap) public onlyOwner {
require(_transactionCap > 0, "Quantity must be more than zero");
transactionCap[_id] = _transactionCap;
}
function canMintQtyForTransaction(uint256 _id, uint256 _qty) internal view returns(bool) {
return _qty <= transactionCap[_id];
}
}
| abstract contract hasTransactionCap is Ownable {
mapping (uint256 => uint256) transactionCap;
function getTransactionCapForToken(uint256 _id) public view returns(uint256) {
return transactionCap[_id];
}
function setTransactionCapForToken(uint256 _id, uint256 _transactionCap) public onlyOwner {
require(_transactionCap > 0, "Quantity must be more than zero");
transactionCap[_id] = _transactionCap;
}
function canMintQtyForTransaction(uint256 _id, uint256 _qty) internal view returns(bool) {
return _qty <= transactionCap[_id];
}
}
| 36,564 |
10 | // See {IERC165-supportsInterface}. | function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IERC165).interfaceId ||
interfaceId == type(IERC20).interfaceId ||
interfaceId == type(IERC20Detailed).interfaceId ||
interfaceId == type(IERC20Metadata).interfaceId ||
interfaceId == type(IERC20Allowance).interfaceId ||
interfaceId == type(IERC20BatchTransfers).interfaceId ||
interfaceId == type(IERC20SafeTransfers).interfaceId ||
interfaceId == type(IERC20Permit).interfaceId;
| function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IERC165).interfaceId ||
interfaceId == type(IERC20).interfaceId ||
interfaceId == type(IERC20Detailed).interfaceId ||
interfaceId == type(IERC20Metadata).interfaceId ||
interfaceId == type(IERC20Allowance).interfaceId ||
interfaceId == type(IERC20BatchTransfers).interfaceId ||
interfaceId == type(IERC20SafeTransfers).interfaceId ||
interfaceId == type(IERC20Permit).interfaceId;
| 54,526 |
17 | // What is the balance of a particular account? | function balanceOf(address _owner) view public returns (uint256 balance) {
return balances[_owner];
}
| function balanceOf(address _owner) view public returns (uint256 balance) {
return balances[_owner];
}
| 17,535 |
256 | // Sets a new comptroller for the marketAdmin function to set a new comptroller return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
| function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
| 21,016 |
130 | // when sell | else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
} else if (!_isExcludedMaxTransactionAmount[to]) {
| else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
} else if (!_isExcludedMaxTransactionAmount[to]) {
| 77,263 |
41 | // Called inside `withdraw` method after updating internal balances/to the receiver of the staking tokens/amount amount to unstake | function _doWithdrawTransfer(
address,
address to,
uint256 amount
| function _doWithdrawTransfer(
address,
address to,
uint256 amount
| 57,609 |
0 | // The address interpreted as native token of the chain. | address public constant NATIVE_TOKEN =
address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
| address public constant NATIVE_TOKEN =
address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
| 11,054 |
44 | // Function that returns the (dynamic) pricing for buys, sells and fee | function pricing(uint scale) public view returns (uint buyPrice, uint sellPrice, uint fee) {
uint buy_eth = scaleFactor * getPriceForBonds( scale, true) / ( scaleFactor - fluxFee(scaleFactor) ) ;
uint sell_eth = getPriceForBonds(scale, false);
sell_eth -= fluxFee(sell_eth);
return ( buy_eth, sell_eth, fluxFee(scale) );
}
| function pricing(uint scale) public view returns (uint buyPrice, uint sellPrice, uint fee) {
uint buy_eth = scaleFactor * getPriceForBonds( scale, true) / ( scaleFactor - fluxFee(scaleFactor) ) ;
uint sell_eth = getPriceForBonds(scale, false);
sell_eth -= fluxFee(sell_eth);
return ( buy_eth, sell_eth, fluxFee(scale) );
}
| 32,894 |
22 | // include in acts | acts[i] = act;
| acts[i] = act;
| 19,331 |
51 | // MintableERC721 libraryImplements the base logic for MintableERC721 / | library MintableERC721Logic {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function executeTransfer(
MintableERC721Data storage erc721Data,
IPool POOL,
bool ATOMIC_PRICING,
address from,
address to,
uint256 tokenId
) public {
require(
erc721Data.owners[tokenId] == from,
"ERC721: transfer from incorrect owner"
);
require(to != address(0), "ERC721: transfer to the zero address");
require(
!isAuctioned(erc721Data, POOL, tokenId),
Errors.TOKEN_IN_AUCTION
);
_beforeTokenTransfer(erc721Data, from, to, tokenId);
// Clear approvals from the previous owner
_approve(erc721Data, address(0), tokenId);
uint64 oldSenderBalance = erc721Data.userState[from].balance;
erc721Data.userState[from].balance = oldSenderBalance - 1;
uint64 oldRecipientBalance = erc721Data.userState[to].balance;
uint64 newRecipientBalance = oldRecipientBalance + 1;
_checkBalanceLimit(erc721Data, ATOMIC_PRICING, newRecipientBalance);
erc721Data.userState[to].balance = newRecipientBalance;
erc721Data.owners[tokenId] = to;
if (from != to && erc721Data.auctions[tokenId].startTime > 0) {
delete erc721Data.auctions[tokenId];
}
IRewardController rewardControllerLocal = erc721Data.rewardController;
if (address(rewardControllerLocal) != address(0)) {
uint256 oldTotalSupply = erc721Data.allTokens.length;
rewardControllerLocal.handleAction(
from,
oldTotalSupply,
oldSenderBalance
);
if (from != to) {
rewardControllerLocal.handleAction(
to,
oldTotalSupply,
oldRecipientBalance
);
}
}
emit Transfer(from, to, tokenId);
}
function executeTransferCollateralizable(
MintableERC721Data storage erc721Data,
IPool POOL,
bool ATOMIC_PRICING,
address from,
address to,
uint256 tokenId
) external returns (bool isUsedAsCollateral_) {
isUsedAsCollateral_ = erc721Data.isUsedAsCollateral[tokenId];
if (from != to && isUsedAsCollateral_) {
erc721Data.userState[from].collateralizedBalance -= 1;
delete erc721Data.isUsedAsCollateral[tokenId];
}
executeTransfer(erc721Data, POOL, ATOMIC_PRICING, from, to, tokenId);
}
function executeSetIsUsedAsCollateral(
MintableERC721Data storage erc721Data,
IPool POOL,
uint256 tokenId,
bool useAsCollateral,
address sender
) internal returns (bool) {
if (erc721Data.isUsedAsCollateral[tokenId] == useAsCollateral)
return false;
address owner = erc721Data.owners[tokenId];
require(owner == sender, "not owner");
if (!useAsCollateral) {
require(
!isAuctioned(erc721Data, POOL, tokenId),
Errors.TOKEN_IN_AUCTION
);
}
uint64 collateralizedBalance = erc721Data
.userState[owner]
.collateralizedBalance;
erc721Data.isUsedAsCollateral[tokenId] = useAsCollateral;
collateralizedBalance = useAsCollateral
? collateralizedBalance + 1
: collateralizedBalance - 1;
erc721Data
.userState[owner]
.collateralizedBalance = collateralizedBalance;
return true;
}
function executeMintMultiple(
MintableERC721Data storage erc721Data,
bool ATOMIC_PRICING,
address to,
DataTypes.ERC721SupplyParams[] calldata tokenData
)
external
returns (
uint64 oldCollateralizedBalance,
uint64 newCollateralizedBalance
)
{
require(to != address(0), "ERC721: mint to the zero address");
uint64 oldBalance = erc721Data.userState[to].balance;
oldCollateralizedBalance = erc721Data
.userState[to]
.collateralizedBalance;
uint256 oldTotalSupply = erc721Data.allTokens.length;
uint64 collateralizedTokens = 0;
for (uint256 index = 0; index < tokenData.length; index++) {
uint256 tokenId = tokenData[index].tokenId;
require(
!_exists(erc721Data, tokenId),
"ERC721: token already minted"
);
_addTokenToAllTokensEnumeration(
erc721Data,
tokenId,
oldTotalSupply + index
);
_addTokenToOwnerEnumeration(
erc721Data,
to,
tokenId,
oldBalance + index
);
erc721Data.owners[tokenId] = to;
if (
tokenData[index].useAsCollateral &&
!erc721Data.isUsedAsCollateral[tokenId]
) {
erc721Data.isUsedAsCollateral[tokenId] = true;
collateralizedTokens++;
}
emit Transfer(address(0), to, tokenId);
}
newCollateralizedBalance =
oldCollateralizedBalance +
collateralizedTokens;
erc721Data
.userState[to]
.collateralizedBalance = newCollateralizedBalance;
uint64 newBalance = oldBalance + uint64(tokenData.length);
_checkBalanceLimit(erc721Data, ATOMIC_PRICING, newBalance);
erc721Data.userState[to].balance = newBalance;
// calculate incentives
IRewardController rewardControllerLocal = erc721Data.rewardController;
if (address(rewardControllerLocal) != address(0)) {
rewardControllerLocal.handleAction(to, oldTotalSupply, oldBalance);
}
return (oldCollateralizedBalance, newCollateralizedBalance);
}
function executeBurnMultiple(
MintableERC721Data storage erc721Data,
IPool POOL,
address user,
uint256[] calldata tokenIds
)
external
returns (
uint64 oldCollateralizedBalance,
uint64 newCollateralizedBalance
)
{
uint64 burntCollateralizedTokens = 0;
uint64 balanceToBurn;
uint256 oldTotalSupply = erc721Data.allTokens.length;
uint256 oldBalance = erc721Data.userState[user].balance;
oldCollateralizedBalance = erc721Data
.userState[user]
.collateralizedBalance;
for (uint256 index = 0; index < tokenIds.length; index++) {
uint256 tokenId = tokenIds[index];
address owner = erc721Data.owners[tokenId];
require(owner == user, "not the owner of Ntoken");
require(
!isAuctioned(erc721Data, POOL, tokenId),
Errors.TOKEN_IN_AUCTION
);
_removeTokenFromAllTokensEnumeration(
erc721Data,
tokenId,
oldTotalSupply - index
);
_removeTokenFromOwnerEnumeration(
erc721Data,
user,
tokenId,
oldBalance - index
);
// Clear approvals
_approve(erc721Data, address(0), tokenId);
balanceToBurn++;
delete erc721Data.owners[tokenId];
if (erc721Data.auctions[tokenId].startTime > 0) {
delete erc721Data.auctions[tokenId];
}
if (erc721Data.isUsedAsCollateral[tokenId]) {
delete erc721Data.isUsedAsCollateral[tokenId];
burntCollateralizedTokens++;
}
emit Transfer(owner, address(0), tokenId);
}
erc721Data.userState[user].balance -= balanceToBurn;
newCollateralizedBalance =
oldCollateralizedBalance -
burntCollateralizedTokens;
erc721Data
.userState[user]
.collateralizedBalance = newCollateralizedBalance;
// calculate incentives
IRewardController rewardControllerLocal = erc721Data.rewardController;
if (address(rewardControllerLocal) != address(0)) {
rewardControllerLocal.handleAction(
user,
oldTotalSupply,
oldBalance
);
}
return (oldCollateralizedBalance, newCollateralizedBalance);
}
function executeApprove(
MintableERC721Data storage erc721Data,
address to,
uint256 tokenId
) external {
_approve(erc721Data, to, tokenId);
}
function _approve(
MintableERC721Data storage erc721Data,
address to,
uint256 tokenId
) private {
erc721Data.tokenApprovals[tokenId] = to;
emit Approval(erc721Data.owners[tokenId], to, tokenId);
}
function executeApprovalForAll(
MintableERC721Data storage erc721Data,
address owner,
address operator,
bool approved
) external {
require(owner != operator, "ERC721: approve to caller");
erc721Data.operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
function executeStartAuction(
MintableERC721Data storage erc721Data,
IPool POOL,
uint256 tokenId
) external {
require(
!isAuctioned(erc721Data, POOL, tokenId),
Errors.AUCTION_ALREADY_STARTED
);
require(
_exists(erc721Data, tokenId),
"ERC721: startAuction for nonexistent token"
);
erc721Data.auctions[tokenId] = DataTypes.Auction({
startTime: block.timestamp
});
}
function executeEndAuction(
MintableERC721Data storage erc721Data,
IPool POOL,
uint256 tokenId
) external {
require(
isAuctioned(erc721Data, POOL, tokenId),
Errors.AUCTION_NOT_STARTED
);
require(
_exists(erc721Data, tokenId),
"ERC721: endAuction for nonexistent token"
);
delete erc721Data.auctions[tokenId];
}
function _checkBalanceLimit(
MintableERC721Data storage erc721Data,
bool ATOMIC_PRICING,
uint64 balance
) private view {
if (ATOMIC_PRICING) {
uint64 balanceLimit = erc721Data.balanceLimit;
require(
balanceLimit == 0 || balance <= balanceLimit,
Errors.NTOKEN_BALANCE_EXCEEDED
);
}
}
function _exists(MintableERC721Data storage erc721Data, uint256 tokenId)
private
view
returns (bool)
{
return erc721Data.owners[tokenId] != address(0);
}
function isAuctioned(
MintableERC721Data storage erc721Data,
IPool POOL,
uint256 tokenId
) public view returns (bool) {
return
erc721Data.auctions[tokenId].startTime >
POOL
.getUserConfiguration(erc721Data.owners[tokenId])
.auctionValidityTime;
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
MintableERC721Data storage erc721Data,
address from,
address to,
uint256 tokenId
) private {
if (from == address(0)) {
uint256 length = erc721Data.allTokens.length;
_addTokenToAllTokensEnumeration(erc721Data, tokenId, length);
} else if (from != to) {
uint256 userBalance = erc721Data.userState[from].balance;
_removeTokenFromOwnerEnumeration(
erc721Data,
from,
tokenId,
userBalance
);
}
if (to == address(0)) {
uint256 length = erc721Data.allTokens.length;
_removeTokenFromAllTokensEnumeration(erc721Data, tokenId, length);
} else if (to != from) {
uint256 length = erc721Data.userState[to].balance;
_addTokenToOwnerEnumeration(erc721Data, to, tokenId, length);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(
MintableERC721Data storage erc721Data,
address to,
uint256 tokenId,
uint256 length
) private {
erc721Data.ownedTokens[to][length] = tokenId;
erc721Data.ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(
MintableERC721Data storage erc721Data,
uint256 tokenId,
uint256 length
) private {
erc721Data.allTokensIndex[tokenId] = length;
erc721Data.allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(
MintableERC721Data storage erc721Data,
address from,
uint256 tokenId,
uint256 userBalance
) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = userBalance - 1;
uint256 tokenIndex = erc721Data.ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = erc721Data.ownedTokens[from][lastTokenIndex];
erc721Data.ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
erc721Data.ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete erc721Data.ownedTokensIndex[tokenId];
delete erc721Data.ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(
MintableERC721Data storage erc721Data,
uint256 tokenId,
uint256 length
) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = length - 1;
uint256 tokenIndex = erc721Data.allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = erc721Data.allTokens[lastTokenIndex];
erc721Data.allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
erc721Data.allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete erc721Data.allTokensIndex[tokenId];
erc721Data.allTokens.pop();
}
}
| library MintableERC721Logic {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function executeTransfer(
MintableERC721Data storage erc721Data,
IPool POOL,
bool ATOMIC_PRICING,
address from,
address to,
uint256 tokenId
) public {
require(
erc721Data.owners[tokenId] == from,
"ERC721: transfer from incorrect owner"
);
require(to != address(0), "ERC721: transfer to the zero address");
require(
!isAuctioned(erc721Data, POOL, tokenId),
Errors.TOKEN_IN_AUCTION
);
_beforeTokenTransfer(erc721Data, from, to, tokenId);
// Clear approvals from the previous owner
_approve(erc721Data, address(0), tokenId);
uint64 oldSenderBalance = erc721Data.userState[from].balance;
erc721Data.userState[from].balance = oldSenderBalance - 1;
uint64 oldRecipientBalance = erc721Data.userState[to].balance;
uint64 newRecipientBalance = oldRecipientBalance + 1;
_checkBalanceLimit(erc721Data, ATOMIC_PRICING, newRecipientBalance);
erc721Data.userState[to].balance = newRecipientBalance;
erc721Data.owners[tokenId] = to;
if (from != to && erc721Data.auctions[tokenId].startTime > 0) {
delete erc721Data.auctions[tokenId];
}
IRewardController rewardControllerLocal = erc721Data.rewardController;
if (address(rewardControllerLocal) != address(0)) {
uint256 oldTotalSupply = erc721Data.allTokens.length;
rewardControllerLocal.handleAction(
from,
oldTotalSupply,
oldSenderBalance
);
if (from != to) {
rewardControllerLocal.handleAction(
to,
oldTotalSupply,
oldRecipientBalance
);
}
}
emit Transfer(from, to, tokenId);
}
function executeTransferCollateralizable(
MintableERC721Data storage erc721Data,
IPool POOL,
bool ATOMIC_PRICING,
address from,
address to,
uint256 tokenId
) external returns (bool isUsedAsCollateral_) {
isUsedAsCollateral_ = erc721Data.isUsedAsCollateral[tokenId];
if (from != to && isUsedAsCollateral_) {
erc721Data.userState[from].collateralizedBalance -= 1;
delete erc721Data.isUsedAsCollateral[tokenId];
}
executeTransfer(erc721Data, POOL, ATOMIC_PRICING, from, to, tokenId);
}
function executeSetIsUsedAsCollateral(
MintableERC721Data storage erc721Data,
IPool POOL,
uint256 tokenId,
bool useAsCollateral,
address sender
) internal returns (bool) {
if (erc721Data.isUsedAsCollateral[tokenId] == useAsCollateral)
return false;
address owner = erc721Data.owners[tokenId];
require(owner == sender, "not owner");
if (!useAsCollateral) {
require(
!isAuctioned(erc721Data, POOL, tokenId),
Errors.TOKEN_IN_AUCTION
);
}
uint64 collateralizedBalance = erc721Data
.userState[owner]
.collateralizedBalance;
erc721Data.isUsedAsCollateral[tokenId] = useAsCollateral;
collateralizedBalance = useAsCollateral
? collateralizedBalance + 1
: collateralizedBalance - 1;
erc721Data
.userState[owner]
.collateralizedBalance = collateralizedBalance;
return true;
}
function executeMintMultiple(
MintableERC721Data storage erc721Data,
bool ATOMIC_PRICING,
address to,
DataTypes.ERC721SupplyParams[] calldata tokenData
)
external
returns (
uint64 oldCollateralizedBalance,
uint64 newCollateralizedBalance
)
{
require(to != address(0), "ERC721: mint to the zero address");
uint64 oldBalance = erc721Data.userState[to].balance;
oldCollateralizedBalance = erc721Data
.userState[to]
.collateralizedBalance;
uint256 oldTotalSupply = erc721Data.allTokens.length;
uint64 collateralizedTokens = 0;
for (uint256 index = 0; index < tokenData.length; index++) {
uint256 tokenId = tokenData[index].tokenId;
require(
!_exists(erc721Data, tokenId),
"ERC721: token already minted"
);
_addTokenToAllTokensEnumeration(
erc721Data,
tokenId,
oldTotalSupply + index
);
_addTokenToOwnerEnumeration(
erc721Data,
to,
tokenId,
oldBalance + index
);
erc721Data.owners[tokenId] = to;
if (
tokenData[index].useAsCollateral &&
!erc721Data.isUsedAsCollateral[tokenId]
) {
erc721Data.isUsedAsCollateral[tokenId] = true;
collateralizedTokens++;
}
emit Transfer(address(0), to, tokenId);
}
newCollateralizedBalance =
oldCollateralizedBalance +
collateralizedTokens;
erc721Data
.userState[to]
.collateralizedBalance = newCollateralizedBalance;
uint64 newBalance = oldBalance + uint64(tokenData.length);
_checkBalanceLimit(erc721Data, ATOMIC_PRICING, newBalance);
erc721Data.userState[to].balance = newBalance;
// calculate incentives
IRewardController rewardControllerLocal = erc721Data.rewardController;
if (address(rewardControllerLocal) != address(0)) {
rewardControllerLocal.handleAction(to, oldTotalSupply, oldBalance);
}
return (oldCollateralizedBalance, newCollateralizedBalance);
}
function executeBurnMultiple(
MintableERC721Data storage erc721Data,
IPool POOL,
address user,
uint256[] calldata tokenIds
)
external
returns (
uint64 oldCollateralizedBalance,
uint64 newCollateralizedBalance
)
{
uint64 burntCollateralizedTokens = 0;
uint64 balanceToBurn;
uint256 oldTotalSupply = erc721Data.allTokens.length;
uint256 oldBalance = erc721Data.userState[user].balance;
oldCollateralizedBalance = erc721Data
.userState[user]
.collateralizedBalance;
for (uint256 index = 0; index < tokenIds.length; index++) {
uint256 tokenId = tokenIds[index];
address owner = erc721Data.owners[tokenId];
require(owner == user, "not the owner of Ntoken");
require(
!isAuctioned(erc721Data, POOL, tokenId),
Errors.TOKEN_IN_AUCTION
);
_removeTokenFromAllTokensEnumeration(
erc721Data,
tokenId,
oldTotalSupply - index
);
_removeTokenFromOwnerEnumeration(
erc721Data,
user,
tokenId,
oldBalance - index
);
// Clear approvals
_approve(erc721Data, address(0), tokenId);
balanceToBurn++;
delete erc721Data.owners[tokenId];
if (erc721Data.auctions[tokenId].startTime > 0) {
delete erc721Data.auctions[tokenId];
}
if (erc721Data.isUsedAsCollateral[tokenId]) {
delete erc721Data.isUsedAsCollateral[tokenId];
burntCollateralizedTokens++;
}
emit Transfer(owner, address(0), tokenId);
}
erc721Data.userState[user].balance -= balanceToBurn;
newCollateralizedBalance =
oldCollateralizedBalance -
burntCollateralizedTokens;
erc721Data
.userState[user]
.collateralizedBalance = newCollateralizedBalance;
// calculate incentives
IRewardController rewardControllerLocal = erc721Data.rewardController;
if (address(rewardControllerLocal) != address(0)) {
rewardControllerLocal.handleAction(
user,
oldTotalSupply,
oldBalance
);
}
return (oldCollateralizedBalance, newCollateralizedBalance);
}
function executeApprove(
MintableERC721Data storage erc721Data,
address to,
uint256 tokenId
) external {
_approve(erc721Data, to, tokenId);
}
function _approve(
MintableERC721Data storage erc721Data,
address to,
uint256 tokenId
) private {
erc721Data.tokenApprovals[tokenId] = to;
emit Approval(erc721Data.owners[tokenId], to, tokenId);
}
function executeApprovalForAll(
MintableERC721Data storage erc721Data,
address owner,
address operator,
bool approved
) external {
require(owner != operator, "ERC721: approve to caller");
erc721Data.operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
function executeStartAuction(
MintableERC721Data storage erc721Data,
IPool POOL,
uint256 tokenId
) external {
require(
!isAuctioned(erc721Data, POOL, tokenId),
Errors.AUCTION_ALREADY_STARTED
);
require(
_exists(erc721Data, tokenId),
"ERC721: startAuction for nonexistent token"
);
erc721Data.auctions[tokenId] = DataTypes.Auction({
startTime: block.timestamp
});
}
function executeEndAuction(
MintableERC721Data storage erc721Data,
IPool POOL,
uint256 tokenId
) external {
require(
isAuctioned(erc721Data, POOL, tokenId),
Errors.AUCTION_NOT_STARTED
);
require(
_exists(erc721Data, tokenId),
"ERC721: endAuction for nonexistent token"
);
delete erc721Data.auctions[tokenId];
}
function _checkBalanceLimit(
MintableERC721Data storage erc721Data,
bool ATOMIC_PRICING,
uint64 balance
) private view {
if (ATOMIC_PRICING) {
uint64 balanceLimit = erc721Data.balanceLimit;
require(
balanceLimit == 0 || balance <= balanceLimit,
Errors.NTOKEN_BALANCE_EXCEEDED
);
}
}
function _exists(MintableERC721Data storage erc721Data, uint256 tokenId)
private
view
returns (bool)
{
return erc721Data.owners[tokenId] != address(0);
}
function isAuctioned(
MintableERC721Data storage erc721Data,
IPool POOL,
uint256 tokenId
) public view returns (bool) {
return
erc721Data.auctions[tokenId].startTime >
POOL
.getUserConfiguration(erc721Data.owners[tokenId])
.auctionValidityTime;
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
MintableERC721Data storage erc721Data,
address from,
address to,
uint256 tokenId
) private {
if (from == address(0)) {
uint256 length = erc721Data.allTokens.length;
_addTokenToAllTokensEnumeration(erc721Data, tokenId, length);
} else if (from != to) {
uint256 userBalance = erc721Data.userState[from].balance;
_removeTokenFromOwnerEnumeration(
erc721Data,
from,
tokenId,
userBalance
);
}
if (to == address(0)) {
uint256 length = erc721Data.allTokens.length;
_removeTokenFromAllTokensEnumeration(erc721Data, tokenId, length);
} else if (to != from) {
uint256 length = erc721Data.userState[to].balance;
_addTokenToOwnerEnumeration(erc721Data, to, tokenId, length);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(
MintableERC721Data storage erc721Data,
address to,
uint256 tokenId,
uint256 length
) private {
erc721Data.ownedTokens[to][length] = tokenId;
erc721Data.ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(
MintableERC721Data storage erc721Data,
uint256 tokenId,
uint256 length
) private {
erc721Data.allTokensIndex[tokenId] = length;
erc721Data.allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(
MintableERC721Data storage erc721Data,
address from,
uint256 tokenId,
uint256 userBalance
) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = userBalance - 1;
uint256 tokenIndex = erc721Data.ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = erc721Data.ownedTokens[from][lastTokenIndex];
erc721Data.ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
erc721Data.ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete erc721Data.ownedTokensIndex[tokenId];
delete erc721Data.ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(
MintableERC721Data storage erc721Data,
uint256 tokenId,
uint256 length
) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = length - 1;
uint256 tokenIndex = erc721Data.allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = erc721Data.allTokens[lastTokenIndex];
erc721Data.allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
erc721Data.allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete erc721Data.allTokensIndex[tokenId];
erc721Data.allTokens.pop();
}
}
| 11,341 |
61 | // Authorize a third party operator to manage (send) msg.sender's asset operator address to be approved authorized bool set to true to authorize, false to withdraw authorization / | function setApprovalForAll(address operator, bool authorized) public {
if (authorized) {
require(!isApprovedForAll(operator, msg.sender));
_addAuthorization(operator, msg.sender);
} else {
require(isApprovedForAll(operator, msg.sender));
_clearAuthorization(operator, msg.sender);
}
ApprovalForAll(operator, msg.sender, authorized);
}
| function setApprovalForAll(address operator, bool authorized) public {
if (authorized) {
require(!isApprovedForAll(operator, msg.sender));
_addAuthorization(operator, msg.sender);
} else {
require(isApprovedForAll(operator, msg.sender));
_clearAuthorization(operator, msg.sender);
}
ApprovalForAll(operator, msg.sender, authorized);
}
| 53,815 |
56 | // See {IERC721Metadata-tokenURI}. / | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
| function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
| 3,133 |
7 | // This contract can accept ETH without calldata | receive() external payable {}
// This contract can accept ETH with calldata
// However, to support EIP 721 and EIP 1155, we need to respond to those methods with their own method signature
fallback() external payable {
bytes4 method = msg.sig;
if (
method == 0x150b7a02 // bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
|| method == 0xf23a6e61 // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
|| method == 0xbc197c81 // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
) {
// Copy back the method
// solhint-disable-next-line no-inline-assembly
assembly {
calldatacopy(0, 0, 0x04)
return (0, 0x20)
}
}
}
| receive() external payable {}
// This contract can accept ETH with calldata
// However, to support EIP 721 and EIP 1155, we need to respond to those methods with their own method signature
fallback() external payable {
bytes4 method = msg.sig;
if (
method == 0x150b7a02 // bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
|| method == 0xf23a6e61 // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
|| method == 0xbc197c81 // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
) {
// Copy back the method
// solhint-disable-next-line no-inline-assembly
assembly {
calldatacopy(0, 0, 0x04)
return (0, 0x20)
}
}
}
| 27,180 |
40 | // See {IERC721Enumerable-tokenByIndex}.return tokenId at index / | function tokenByIndex(uint256 index)
public
override
view
returns (uint256)
{
if(_exists(index)) {
return index;
} else {
| function tokenByIndex(uint256 index)
public
override
view
returns (uint256)
{
if(_exists(index)) {
return index;
} else {
| 34,068 |
43 | // This is to prevent the owner from front running its name curators signal by posting its own signal ahead, bringing the name curators in, and dumping on them | ICuration curation = curation();
require(
!curation.isCurated(_subgraphDeploymentID),
"GNS: Owner cannot point to a subgraphID that has been pre-curated"
);
| ICuration curation = curation();
require(
!curation.isCurated(_subgraphDeploymentID),
"GNS: Owner cannot point to a subgraphID that has been pre-curated"
);
| 29,834 |
14 | // Mapping from uid of an auction listing => current winning bid in an auction. | mapping(uint256 => Offer) public winningBid;
/*///////////////////////////////////////////////////////////////
Modifiers
| mapping(uint256 => Offer) public winningBid;
/*///////////////////////////////////////////////////////////////
Modifiers
| 4,063 |
44 | // Emit log events / | TokensSent(msg.sender, tokens);
ContributionReceived(msg.sender, msg.value);
Transfer(owner, msg.sender, tokens);
return true;
| TokensSent(msg.sender, tokens);
ContributionReceived(msg.sender, msg.value);
Transfer(owner, msg.sender, tokens);
return true;
| 81,240 |
59 | // This default function can receive Ether or perform queries to modules/using bound methods. | fallback()
external
payable
| fallback()
external
payable
| 47,072 |
28 | // Returns the amount of `debtShares` that will be burned by paying back`debt` amount.debt to checkRequirements:- Must not revert. / | function previewPayback(uint256 debt) external view returns (uint256 shares);
| function previewPayback(uint256 debt) external view returns (uint256 shares);
| 11,887 |
33 | // token balance before swap | uint balanceBefore = IERC20(toTokenContract).balanceOf(msg.sender);
| uint balanceBefore = IERC20(toTokenContract).balanceOf(msg.sender);
| 13,078 |
6 | // Check the first field is 0x20 (because we have only a single return value) | uint256 argptr;
assembly {
argptr := mload(add(output, 32))
}
| uint256 argptr;
assembly {
argptr := mload(add(output, 32))
}
| 37,789 |
146 | // calculate prize | prize=paid(assistant,helper,myid);
| prize=paid(assistant,helper,myid);
| 46,401 |
57 | // Deploy proxy for ConversionHandler contract | address proxyConversions = createProxyForCampaign("TOKEN_SELL","TwoKeyConversionHandler");
| address proxyConversions = createProxyForCampaign("TOKEN_SELL","TwoKeyConversionHandler");
| 24,391 |
173 | // Short string. |
uint256 strLen = prefix - 0x80;
require(_in.length > strLen, "Invalid RLP short string.");
return (1, strLen, RLPItemType.DATA_ITEM);
|
uint256 strLen = prefix - 0x80;
require(_in.length > strLen, "Invalid RLP short string.");
return (1, strLen, RLPItemType.DATA_ITEM);
| 24,322 |
10 | // Execute membership action to mint or burn shares or loot against whitelisted `minions` in consideration of `msg.sender` & given amounts./shaman Whitelisted contract to trigger action./loot Loot involved in external call./shares Shares involved in external call./mint Confirm whether action involves mint or burn action - if `false`, perform burn./ return lootOut sharesOut Loot and/or shares derived from action. | function memberAction(address shaman, uint96 loot, uint96 shares, bool mint) external nonReentrant payable returns (uint96 lootOut, uint96 sharesOut) {
require(shamans[shaman],'!shaman'); /*check `shaman` is approved*/
if (mint) { /*execute `mint` action*/
(lootOut, sharesOut) = IShaman(shaman).memberAction{value: msg.value}(msg.sender, loot, shares); /*fetch 'reaction' mint per inputs*/
if (lootOut != 0) _mintLoot(msg.sender, lootOut); emit TransferLoot(address(0), msg.sender, lootOut); /*add loot to `msg.sender` account & Baal totals*/
if (sharesOut != 0) _mint(msg.sender, sharesOut); /*add shares to `msg.sender` account & Baal total with erc20 accounting*/
} else { /*otherwise, execute burn action*/
(lootOut, sharesOut) = IShaman(shaman).memberAction{value: msg.value}(msg.sender, loot, shares); /*fetch 'reaction' burn per inputs*/
if (lootOut != 0) _burnLoot(msg.sender, lootOut); emit TransferLoot(msg.sender, address(0), lootOut); /*subtract loot from `msg.sender` account & Baal totals*/
if (sharesOut != 0) _burn(msg.sender, sharesOut); /*subtract shares from `msg.sender` account & Baal total with erc20 accounting*/
}
}
| function memberAction(address shaman, uint96 loot, uint96 shares, bool mint) external nonReentrant payable returns (uint96 lootOut, uint96 sharesOut) {
require(shamans[shaman],'!shaman'); /*check `shaman` is approved*/
if (mint) { /*execute `mint` action*/
(lootOut, sharesOut) = IShaman(shaman).memberAction{value: msg.value}(msg.sender, loot, shares); /*fetch 'reaction' mint per inputs*/
if (lootOut != 0) _mintLoot(msg.sender, lootOut); emit TransferLoot(address(0), msg.sender, lootOut); /*add loot to `msg.sender` account & Baal totals*/
if (sharesOut != 0) _mint(msg.sender, sharesOut); /*add shares to `msg.sender` account & Baal total with erc20 accounting*/
} else { /*otherwise, execute burn action*/
(lootOut, sharesOut) = IShaman(shaman).memberAction{value: msg.value}(msg.sender, loot, shares); /*fetch 'reaction' burn per inputs*/
if (lootOut != 0) _burnLoot(msg.sender, lootOut); emit TransferLoot(msg.sender, address(0), lootOut); /*subtract loot from `msg.sender` account & Baal totals*/
if (sharesOut != 0) _burn(msg.sender, sharesOut); /*subtract shares from `msg.sender` account & Baal total with erc20 accounting*/
}
}
| 9,331 |
19 | // Sets a verified proxy address.Can be done through a multisig wallet in the future. _id Id of the proxy. _proxy Proxy address. / | function setProxy(
| function setProxy(
| 47,350 |
22 | // Returns the account approved for `tokenId` token. Requirements: - `tokenId` must exist. / | function getApproved(uint256 tokenId)
| function getApproved(uint256 tokenId)
| 1,015 |
434 | // Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market market The address of the market to accrue rewards supplier The address of the supplier to accrue rewards isVerified Verified / Public protocol / | function refreshAlkSupplyIndex(
address market,
address supplier,
bool isVerified
| function refreshAlkSupplyIndex(
address market,
address supplier,
bool isVerified
| 12,300 |
0 | // lib/dss-interfaces/src/dapp/DSPauseAbstract.sol/ pragma solidity >=0.5.12; / https:github.com/dapphub/ds-pause | interface DSPauseAbstract {
function owner() external view returns (address);
function authority() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
function setDelay(uint256) external;
function plans(bytes32) external view returns (bool);
function proxy() external view returns (address);
function delay() external view returns (uint256);
function plot(address, bytes32, bytes calldata, uint256) external;
function drop(address, bytes32, bytes calldata, uint256) external;
function exec(address, bytes32, bytes calldata, uint256) external returns (bytes memory);
}
| interface DSPauseAbstract {
function owner() external view returns (address);
function authority() external view returns (address);
function setOwner(address) external;
function setAuthority(address) external;
function setDelay(uint256) external;
function plans(bytes32) external view returns (bool);
function proxy() external view returns (address);
function delay() external view returns (uint256);
function plot(address, bytes32, bytes calldata, uint256) external;
function drop(address, bytes32, bytes calldata, uint256) external;
function exec(address, bytes32, bytes calldata, uint256) external returns (bytes memory);
}
| 1,552 |
32 | // delivery service | payable(address(_customerAddress)).transfer(_dividends);
| payable(address(_customerAddress)).transfer(_dividends);
| 19,231 |
1 | // 260 ~= 1.1e18 so this is sufficient to store the full range of potential AUM fees. | uint256 private constant _AUM_FEE_PCT_WIDTH = 60;
| uint256 private constant _AUM_FEE_PCT_WIDTH = 60;
| 22,088 |
3 | // Whether this maker is allowed to create a new Issuance.Maker is allowed if maker white list is not enabled, or the maker is in the whitelist. / | function isMakerAllowed(address maker) public view returns (bool) {
return !_makerWhitelistEnabled || _makerWhitelist[maker];
}
| function isMakerAllowed(address maker) public view returns (bool) {
return !_makerWhitelistEnabled || _makerWhitelist[maker];
}
| 7,930 |
27 | // toggle alt token state on pool/only governance can call this/_pool pool address for alt token | function toggleActiveAlt(address _pool) external onlyGovernance returns (bool) {
require(poolAltInfo[_pool].altToken != address(0), "TNE");
emit UpdateAltState(
poolInfo[_pool].isAltActive,
poolInfo[_pool].isAltActive = !poolInfo[_pool].isAltActive,
_pool
);
if (poolInfo[_pool].isAltActive) {
updateAltPoolState(_pool);
} else {
poolAltInfo[_pool].lastRewardBlock = block.number;
}
return poolInfo[_pool].isAltActive;
}
| function toggleActiveAlt(address _pool) external onlyGovernance returns (bool) {
require(poolAltInfo[_pool].altToken != address(0), "TNE");
emit UpdateAltState(
poolInfo[_pool].isAltActive,
poolInfo[_pool].isAltActive = !poolInfo[_pool].isAltActive,
_pool
);
if (poolInfo[_pool].isAltActive) {
updateAltPoolState(_pool);
} else {
poolAltInfo[_pool].lastRewardBlock = block.number;
}
return poolInfo[_pool].isAltActive;
}
| 53,850 |
15 | // Change the Tokens contract address | function changeTokensAddress(address _newTokensAddress) external onlyOwner {
tokens = ITokens(_newTokensAddress);
}
| function changeTokensAddress(address _newTokensAddress) external onlyOwner {
tokens = ITokens(_newTokensAddress);
}
| 17,201 |
17 | // Gets the smallest part of the token that is not divisible.return the token granularity / | function granularity() external view override returns (uint256) {
return tokenGranularity;
}
| function granularity() external view override returns (uint256) {
return tokenGranularity;
}
| 28,060 |
3 | // If no xJollof exists, mint it 1:1 to the amount put in | if (totalShares == 0 || totalJollof == 0) {
_mint(msg.sender, _amount);
}
| if (totalShares == 0 || totalJollof == 0) {
_mint(msg.sender, _amount);
}
| 47,525 |
21 | // transfer old hero | (genes,,,,,,level,lockedTo,lockId) = heroesOld.getCharacter(_tokenId);
heroesOld.unlock(_tokenId, lockId);
heroesOld.lock(_tokenId, 0, 999);
heroesOld.transferFrom(msg.sender, address(this), _tokenId);
| (genes,,,,,,level,lockedTo,lockId) = heroesOld.getCharacter(_tokenId);
heroesOld.unlock(_tokenId, lockId);
heroesOld.lock(_tokenId, 0, 999);
heroesOld.transferFrom(msg.sender, address(this), _tokenId);
| 3,702 |
48 | // the given date must be aligned to 8am UTC and the correct offset, otherwise we will end up setting a price on a un-aligned date | require(
date == get8amWeeklyOrDailyAligned(date),
"date is not aligned"
);
| require(
date == get8amWeeklyOrDailyAligned(date),
"date is not aligned"
);
| 32,515 |
221 | // Allows owner to set Max mints per tx _newMaxMint maximum amount of tokens allowed to mint per tx. Must be >= 1 / | function setMaxMint(uint256 _newMaxMint) public onlyOwner {
require(_newMaxMint >= 1, "Max mint must be at least 1");
maxBatchSize = _newMaxMint;
}
| function setMaxMint(uint256 _newMaxMint) public onlyOwner {
require(_newMaxMint >= 1, "Max mint must be at least 1");
maxBatchSize = _newMaxMint;
}
| 33,356 |
54 | // 限制批次設置已使用票券票的數量,不能大於 maxMarkedTickets,以避免手續費過高。 | require(_ticketIds.length <= maxMarkedTickets, "set too many tickets in the same time");
| require(_ticketIds.length <= maxMarkedTickets, "set too many tickets in the same time");
| 30,273 |
175 | // File: hasTransactionCap.sol | abstract contract hasTransactionCap is Teams {
mapping (uint256 => uint256) transactionCap;
function getTransactionCapForToken(uint256 _id) public view returns(uint256) {
return transactionCap[_id];
}
function setTransactionCapForToken(uint256 _id, uint256 _transactionCap) public onlyTeamOrOwner {
require(_transactionCap > 0, "Quantity must be more than zero");
transactionCap[_id] = _transactionCap;
}
function canMintQtyForTransaction(uint256 _id, uint256 _qty) internal view returns(bool) {
return _qty <= transactionCap[_id];
}
}
| abstract contract hasTransactionCap is Teams {
mapping (uint256 => uint256) transactionCap;
function getTransactionCapForToken(uint256 _id) public view returns(uint256) {
return transactionCap[_id];
}
function setTransactionCapForToken(uint256 _id, uint256 _transactionCap) public onlyTeamOrOwner {
require(_transactionCap > 0, "Quantity must be more than zero");
transactionCap[_id] = _transactionCap;
}
function canMintQtyForTransaction(uint256 _id, uint256 _qty) internal view returns(bool) {
return _qty <= transactionCap[_id];
}
}
| 12,061 |
141 | // register the supported interfaces to conform to ERC1363 via ERC165 | _registerInterface(_INTERFACE_ID_ERC1363_TRANSFER);
_registerInterface(_INTERFACE_ID_ERC1363_APPROVE);
| _registerInterface(_INTERFACE_ID_ERC1363_TRANSFER);
_registerInterface(_INTERFACE_ID_ERC1363_APPROVE);
| 6,436 |
95 | // IRatesProvider IRatesProvider interfaceCyril Lapinte - <cyril.lapinte@openfiz.com> / | abstract contract IRatesProvider {
function defineRatesExternal(uint256[] calldata _rates) virtual external returns (bool);
function name() virtual public view returns (string memory);
function rate(bytes32 _currency) virtual public view returns (uint256);
function currencies() virtual public view
returns (bytes32[] memory, uint256[] memory, uint256);
function rates() virtual public view returns (uint256, uint256[] memory);
function convert(uint256 _amount, bytes32 _fromCurrency, bytes32 _toCurrency)
virtual public view returns (uint256);
function defineCurrencies(
bytes32[] memory _currencies,
uint256[] memory _decimals,
uint256 _rateOffset) virtual public returns (bool);
function defineRates(uint256[] memory _rates) virtual public returns (bool);
event RateOffset(uint256 rateOffset);
event Currencies(bytes32[] currencies, uint256[] decimals);
event Rate(bytes32 indexed currency, uint256 rate);
}
| abstract contract IRatesProvider {
function defineRatesExternal(uint256[] calldata _rates) virtual external returns (bool);
function name() virtual public view returns (string memory);
function rate(bytes32 _currency) virtual public view returns (uint256);
function currencies() virtual public view
returns (bytes32[] memory, uint256[] memory, uint256);
function rates() virtual public view returns (uint256, uint256[] memory);
function convert(uint256 _amount, bytes32 _fromCurrency, bytes32 _toCurrency)
virtual public view returns (uint256);
function defineCurrencies(
bytes32[] memory _currencies,
uint256[] memory _decimals,
uint256 _rateOffset) virtual public returns (bool);
function defineRates(uint256[] memory _rates) virtual public returns (bool);
event RateOffset(uint256 rateOffset);
event Currencies(bytes32[] currencies, uint256[] decimals);
event Rate(bytes32 indexed currency, uint256 rate);
}
| 48,050 |
5 | // check if the sender already has a username | require(balanceOf(msg.sender) == 0, "You have a username");
uint256 supply = totalSupply();
| require(balanceOf(msg.sender) == 0, "You have a username");
uint256 supply = totalSupply();
| 10,087 |
16 | // Returns the index of the next element to be enqueued.return Index for the next queue element. / slither-disable-next-line external-function | function getNextQueueIndex() public view returns (uint40) {
return _nextQueueIndex;
}
| function getNextQueueIndex() public view returns (uint40) {
return _nextQueueIndex;
}
| 5,487 |
1 | // Assign all tokens to the contract's creator. | constructor(address owner, string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_mint(owner, totalSupply);
}
| constructor(address owner, string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_mint(owner, totalSupply);
}
| 2,844 |
0 | // Initial distribution for the first 24h genesis pools | uint256 public constant INITIAL_GENESIS_POOL_DISTRIBUTION = 2400 ether;
| uint256 public constant INITIAL_GENESIS_POOL_DISTRIBUTION = 2400 ether;
| 15,926 |
40 | // withdraw foreign tokens / | function withdrawForeignTokens(address tokenContract) onlyAdmin public returns (bool) {
ForeignToken token = ForeignToken(tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(admin, amount);
}
| function withdrawForeignTokens(address tokenContract) onlyAdmin public returns (bool) {
ForeignToken token = ForeignToken(tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(admin, amount);
}
| 12,674 |
28 | // TRANSFER FUNCTIONS |
function transfer(address to, uint256 value)
public
|
function transfer(address to, uint256 value)
public
| 4,599 |
4 | // Sets the liquidation threshold of the reserve self The reserve configuration threshold The new liquidation threshold / | {
require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.INVALID_LIQ_THRESHOLD);
self.data =
(self.data & LIQUIDATION_THRESHOLD_MASK) |
(threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);
}
| {
require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.INVALID_LIQ_THRESHOLD);
self.data =
(self.data & LIQUIDATION_THRESHOLD_MASK) |
(threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);
}
| 36,421 |
80 | // Collection of functions related to array types. / | library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
| library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
| 522 |
3 | // when I want to modify or comment on my previous claim | bytes CLAIM_AMEND_REF = "amend ref";
| bytes CLAIM_AMEND_REF = "amend ref";
| 48,454 |
50 | // Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. _beneficiaries Addresses to be added to the whitelist / | function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
| function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
| 32,005 |
1 | // propose fork_propNewTellorAddress address for new proposed Tellor/ | function propFork(address _propNewTellorAddress) external {
doTransfer(msg.sender,address(this), 10000e18);//This is the fork fee
uint disputeId = disputesIds.length + 1;
disputes[disputeId] = Dispute({
isPropFork: true,
reportedMiner: msg.sender,
reportingParty: msg.sender,
apiId: 0,
timestamp: 0,
value: 0,
minExecutionDate: now + 7 days,
numberOfVotes: 0,
executed: false,
disputeVotePassed: false,
blockNumber: block.number,
tally: 0,
index:disputeId,
quorum: 0
});
disputesIds.push(disputeId);
propForkAddress[disputeId] = _propNewTellorAddress;
}
| function propFork(address _propNewTellorAddress) external {
doTransfer(msg.sender,address(this), 10000e18);//This is the fork fee
uint disputeId = disputesIds.length + 1;
disputes[disputeId] = Dispute({
isPropFork: true,
reportedMiner: msg.sender,
reportingParty: msg.sender,
apiId: 0,
timestamp: 0,
value: 0,
minExecutionDate: now + 7 days,
numberOfVotes: 0,
executed: false,
disputeVotePassed: false,
blockNumber: block.number,
tally: 0,
index:disputeId,
quorum: 0
});
disputesIds.push(disputeId);
propForkAddress[disputeId] = _propNewTellorAddress;
}
| 24,445 |
17 | // logforsale for car added | event ForSale(string message, uint _carId, address seller);
| event ForSale(string message, uint _carId, address seller);
| 31,243 |
11 | // This is a non-standard ERC-20 | success := not(0) // set success to true
| success := not(0) // set success to true
| 4,189 |
42 | // Approve token transfer to cover all possible scenarios | _approve(address(this), address(uniswapV2Router), tokenAmount);
| _approve(address(this), address(uniswapV2Router), tokenAmount);
| 1,693 |
0 | // Verifies that the rebasing is not paused. / | modifier whenNotRebasePaused() {
require(!rebasePaused, "Rebasing paused");
_;
}
| modifier whenNotRebasePaused() {
require(!rebasePaused, "Rebasing paused");
_;
}
| 5,008 |
213 | // Opium.Registry contract keeps addresses of deployed Opium contracts set to allow them route and communicate to each other | contract Registry is RegistryErrors {
// Address of Opium.TokenMinter contract
address private minter;
// Address of Opium.Core contract
address private core;
// Address of Opium.OracleAggregator contract
address private oracleAggregator;
// Address of Opium.SyntheticAggregator contract
address private syntheticAggregator;
// Address of Opium.TokenSpender contract
address private tokenSpender;
// Address of Opium commission receiver
address private opiumAddress;
// Address of Opium contract set deployer
address public initializer;
/// @notice This modifier restricts access to functions, which could be called only by initializer
modifier onlyInitializer() {
require(msg.sender == initializer, ERROR_REGISTRY_ONLY_INITIALIZER);
_;
}
/// @notice Sets initializer
constructor() public {
initializer = msg.sender;
}
// SETTERS
/// @notice Sets Opium.TokenMinter, Opium.Core, Opium.OracleAggregator, Opium.SyntheticAggregator, Opium.TokenSpender, Opium commission receiver addresses and allows to do it only once
/// @param _minter address Address of Opium.TokenMinter
/// @param _core address Address of Opium.Core
/// @param _oracleAggregator address Address of Opium.OracleAggregator
/// @param _syntheticAggregator address Address of Opium.SyntheticAggregator
/// @param _tokenSpender address Address of Opium.TokenSpender
/// @param _opiumAddress address Address of Opium commission receiver
function init(
address _minter,
address _core,
address _oracleAggregator,
address _syntheticAggregator,
address _tokenSpender,
address _opiumAddress
) external onlyInitializer {
require(
minter == address(0) &&
core == address(0) &&
oracleAggregator == address(0) &&
syntheticAggregator == address(0) &&
tokenSpender == address(0) &&
opiumAddress == address(0),
ERROR_REGISTRY_ALREADY_SET
);
require(
_minter != address(0) &&
_core != address(0) &&
_oracleAggregator != address(0) &&
_syntheticAggregator != address(0) &&
_tokenSpender != address(0) &&
_opiumAddress != address(0),
ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS
);
minter = _minter;
core = _core;
oracleAggregator = _oracleAggregator;
syntheticAggregator = _syntheticAggregator;
tokenSpender = _tokenSpender;
opiumAddress = _opiumAddress;
}
/// @notice Allows opium commission receiver address to change itself
/// @param _opiumAddress address New opium commission receiver address
function changeOpiumAddress(address _opiumAddress) external {
require(opiumAddress == msg.sender, ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED);
require(_opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS);
opiumAddress = _opiumAddress;
}
// GETTERS
/// @notice Returns address of Opium.TokenMinter
/// @param result address Address of Opium.TokenMinter
function getMinter() external view returns (address result) {
return minter;
}
/// @notice Returns address of Opium.Core
/// @param result address Address of Opium.Core
function getCore() external view returns (address result) {
return core;
}
/// @notice Returns address of Opium.OracleAggregator
/// @param result address Address of Opium.OracleAggregator
function getOracleAggregator() external view returns (address result) {
return oracleAggregator;
}
/// @notice Returns address of Opium.SyntheticAggregator
/// @param result address Address of Opium.SyntheticAggregator
function getSyntheticAggregator() external view returns (address result) {
return syntheticAggregator;
}
/// @notice Returns address of Opium.TokenSpender
/// @param result address Address of Opium.TokenSpender
function getTokenSpender() external view returns (address result) {
return tokenSpender;
}
/// @notice Returns address of Opium commission receiver
/// @param result address Address of Opium commission receiver
function getOpiumAddress() external view returns (address result) {
return opiumAddress;
}
}
| contract Registry is RegistryErrors {
// Address of Opium.TokenMinter contract
address private minter;
// Address of Opium.Core contract
address private core;
// Address of Opium.OracleAggregator contract
address private oracleAggregator;
// Address of Opium.SyntheticAggregator contract
address private syntheticAggregator;
// Address of Opium.TokenSpender contract
address private tokenSpender;
// Address of Opium commission receiver
address private opiumAddress;
// Address of Opium contract set deployer
address public initializer;
/// @notice This modifier restricts access to functions, which could be called only by initializer
modifier onlyInitializer() {
require(msg.sender == initializer, ERROR_REGISTRY_ONLY_INITIALIZER);
_;
}
/// @notice Sets initializer
constructor() public {
initializer = msg.sender;
}
// SETTERS
/// @notice Sets Opium.TokenMinter, Opium.Core, Opium.OracleAggregator, Opium.SyntheticAggregator, Opium.TokenSpender, Opium commission receiver addresses and allows to do it only once
/// @param _minter address Address of Opium.TokenMinter
/// @param _core address Address of Opium.Core
/// @param _oracleAggregator address Address of Opium.OracleAggregator
/// @param _syntheticAggregator address Address of Opium.SyntheticAggregator
/// @param _tokenSpender address Address of Opium.TokenSpender
/// @param _opiumAddress address Address of Opium commission receiver
function init(
address _minter,
address _core,
address _oracleAggregator,
address _syntheticAggregator,
address _tokenSpender,
address _opiumAddress
) external onlyInitializer {
require(
minter == address(0) &&
core == address(0) &&
oracleAggregator == address(0) &&
syntheticAggregator == address(0) &&
tokenSpender == address(0) &&
opiumAddress == address(0),
ERROR_REGISTRY_ALREADY_SET
);
require(
_minter != address(0) &&
_core != address(0) &&
_oracleAggregator != address(0) &&
_syntheticAggregator != address(0) &&
_tokenSpender != address(0) &&
_opiumAddress != address(0),
ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS
);
minter = _minter;
core = _core;
oracleAggregator = _oracleAggregator;
syntheticAggregator = _syntheticAggregator;
tokenSpender = _tokenSpender;
opiumAddress = _opiumAddress;
}
/// @notice Allows opium commission receiver address to change itself
/// @param _opiumAddress address New opium commission receiver address
function changeOpiumAddress(address _opiumAddress) external {
require(opiumAddress == msg.sender, ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED);
require(_opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS);
opiumAddress = _opiumAddress;
}
// GETTERS
/// @notice Returns address of Opium.TokenMinter
/// @param result address Address of Opium.TokenMinter
function getMinter() external view returns (address result) {
return minter;
}
/// @notice Returns address of Opium.Core
/// @param result address Address of Opium.Core
function getCore() external view returns (address result) {
return core;
}
/// @notice Returns address of Opium.OracleAggregator
/// @param result address Address of Opium.OracleAggregator
function getOracleAggregator() external view returns (address result) {
return oracleAggregator;
}
/// @notice Returns address of Opium.SyntheticAggregator
/// @param result address Address of Opium.SyntheticAggregator
function getSyntheticAggregator() external view returns (address result) {
return syntheticAggregator;
}
/// @notice Returns address of Opium.TokenSpender
/// @param result address Address of Opium.TokenSpender
function getTokenSpender() external view returns (address result) {
return tokenSpender;
}
/// @notice Returns address of Opium commission receiver
/// @param result address Address of Opium commission receiver
function getOpiumAddress() external view returns (address result) {
return opiumAddress;
}
}
| 32,175 |
3 | // uint256s | uint256 MAX_SUPPLY = 10000;
uint256 MINTS_PER_TIER = 2000;
uint256 SEED_NONCE = 0;
| uint256 MAX_SUPPLY = 10000;
uint256 MINTS_PER_TIER = 2000;
uint256 SEED_NONCE = 0;
| 52,538 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.