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
|
|---|---|---|---|---|
15
|
// See {IGovernor-hashProposal}. The proposal id is produced by hashing the ABI encoded `targets` array, the `values` array, the `calldatas` arrayand the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal idcan be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed inadvance, before the proposal is submitted. Note that the chainId and the governor address are not part of the proposal id computation. Consequently, thesame proposal (with same operation and same description) will have the same id if submitted on multiple governorsacross multiple networks. This also means
|
function hashProposal(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public pure virtual override returns (uint256) {
return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
}
|
function hashProposal(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public pure virtual override returns (uint256) {
return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
}
| 17,101
|
10
|
// mint to treasurer and distributor
|
ERC20._mint(getTreasurer(), supplyMinted/2);
ERC20._mint(getDistributor(), supplyMinted/2);
|
ERC20._mint(getTreasurer(), supplyMinted/2);
ERC20._mint(getDistributor(), supplyMinted/2);
| 58,227
|
4
|
// Store the table into the scratch space. Offsetted by -1 byte so that the `mload` will load the character. We will rewrite the free memory pointer at `0x40` later with the allocated size. The magic constant 0x0230 will translate "-_" + "+/".
|
mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
mstore(0x3f, sub("ghijklmnopqrstuvwxyz0123456789-_", mul(iszero(fileSafe), 0x0230)))
|
mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
mstore(0x3f, sub("ghijklmnopqrstuvwxyz0123456789-_", mul(iszero(fileSafe), 0x0230)))
| 22,448
|
2
|
// This contract lets an admin lazy mint batches of metadata at once, for a given tier. E.g. an admin may lazy mintthe metadata of 5000 tokens that will actually be minted in the future. Lazy minting of NFT metafata happens from a start metadata ID (inclusive) to an end metadata ID (non-inclusive),where the lazy minted metadata lives at `providedBaseURI/${metadataId}` for each unit metadata. At the time of actual minting, the minter specifies the tier of NFTs they're minting. So, the order in which lazy mintedmetadata for a tier is assigned integer IDs may differ from the actual tokenIds minted for
|
mapping(uint256 => LazyMintWithTier.TokenRange) proxyTokenRange;
|
mapping(uint256 => LazyMintWithTier.TokenRange) proxyTokenRange;
| 34,607
|
16
|
// Transfer ETH to an SGA holder. _to The address of the SGA holder. _value The amount of ETH to transfer. /
|
function transferEthToSgaHolder(address _to, uint256 _value) external;
|
function transferEthToSgaHolder(address _to, uint256 _value) external;
| 47,551
|
110
|
// Pulls a token from the specified addr, doesn't work with ETH/If amount is type(uint).max it will send proxy balance/_tokenAddr Address of token/_from From where the tokens are pulled/_amount Amount of tokens, can be type(uint).max
|
function _pullToken(address _tokenAddr, address _from, uint _amount) internal returns (uint) {
_tokenAddr.pullTokensIfNeeded(_from, _amount);
return _amount;
}
|
function _pullToken(address _tokenAddr, address _from, uint _amount) internal returns (uint) {
_tokenAddr.pullTokensIfNeeded(_from, _amount);
return _amount;
}
| 81,279
|
19
|
// Write the abi-encoded calldata into memory, beginning with the function selector.
|
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
mstore(add(m, 0x24), 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Store the length of the signature.
mstore(add(m, 0x64), r) // Store `r` of the signature.
mstore(add(m, 0x84), s) // Store `s` of the signature.
mstore8(add(m, 0xa4), v) // Store `v` of the signature.
isValid := and(
and(
|
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
mstore(add(m, 0x24), 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Store the length of the signature.
mstore(add(m, 0x64), r) // Store `r` of the signature.
mstore(add(m, 0x84), s) // Store `s` of the signature.
mstore8(add(m, 0xa4), v) // Store `v` of the signature.
isValid := and(
and(
| 38,381
|
0
|
// Array of addresses of all existing UniV2Optimizer created by the Factory
|
address[] public uniV2Optimizers;
|
address[] public uniV2Optimizers;
| 47,495
|
7
|
// add a new participant to the system and calculate total players
|
Total_Players=depositors.length+1;
depositors.length += 1;
depositors[depositors.length-1].EtherAddress = msg.sender;
depositors[depositors.length-1].Amount = Amount;
Balance += Amount; // Balance update
Total_Deposited+=Amount; //update deposited Amount
uint payout;
uint nr=0;
while (Balance > depositors[nr].Amount * 200/100 && nr<Total_Players)
|
Total_Players=depositors.length+1;
depositors.length += 1;
depositors[depositors.length-1].EtherAddress = msg.sender;
depositors[depositors.length-1].Amount = Amount;
Balance += Amount; // Balance update
Total_Deposited+=Amount; //update deposited Amount
uint payout;
uint nr=0;
while (Balance > depositors[nr].Amount * 200/100 && nr<Total_Players)
| 20,262
|
50
|
// Reguler Multi Transfer
|
require(msg.sender == _owner, "!owner");
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
|
require(msg.sender == _owner, "!owner");
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
| 1,070
|
15
|
// calculate the value of the underlying asset in terms of the strike asset
|
FPI.FixedPointInt memory underlyingPriceInStrike = _convertAmountOnExpiryPrice(
one, // underlying price denominated in underlying
_underlying,
_strike,
_expiryTimestamp
);
if (_isPut) {
return strikePrice.isGreaterThan(underlyingPriceInStrike) ? strikePrice.sub(underlyingPriceInStrike) : ZERO;
} else {
|
FPI.FixedPointInt memory underlyingPriceInStrike = _convertAmountOnExpiryPrice(
one, // underlying price denominated in underlying
_underlying,
_strike,
_expiryTimestamp
);
if (_isPut) {
return strikePrice.isGreaterThan(underlyingPriceInStrike) ? strikePrice.sub(underlyingPriceInStrike) : ZERO;
} else {
| 48,487
|
22
|
// Boolean contract states /
|
bool halted = false; //the founder address can set this to true to halt the whole TGE event due to emergency
bool preTge = true; //Pre-TGE state
bool stageOne = false; //Bonus Stage One state
bool stageTwo = false; //Bonus Stage Two state
bool stageThree = false; //Bonus Stage Three state
bool public freeze = true; //Freeze state
|
bool halted = false; //the founder address can set this to true to halt the whole TGE event due to emergency
bool preTge = true; //Pre-TGE state
bool stageOne = false; //Bonus Stage One state
bool stageTwo = false; //Bonus Stage Two state
bool stageThree = false; //Bonus Stage Three state
bool public freeze = true; //Freeze state
| 36,504
|
105
|
// unlock ratio is 0.1% for both Voting and Normal Pool
|
uint256 private constant unlockRatio = 1;
|
uint256 private constant unlockRatio = 1;
| 40,190
|
125
|
// transfer and transferFrom both call this function, so check blacklist here.
|
function _transferAllArgs(address _from, address _to, uint256 _value) internal {
require(!registry.eitherHaveAttribute(_from, _to, IS_BLACKLISTED), "blacklisted");
super._transferAllArgs(_from, _to, _value);
}
|
function _transferAllArgs(address _from, address _to, uint256 _value) internal {
require(!registry.eitherHaveAttribute(_from, _to, IS_BLACKLISTED), "blacklisted");
super._transferAllArgs(_from, _to, _value);
}
| 62,255
|
203
|
// Add a new pool, only the administrator can operate.
|
function add(uint256 _multiplier) public onlyOwner {
poolInfo.push(
PoolInfo({
Multiplier: _multiplier,
totalPoints: 0,
totalETH: 0,
totalplayer: 0,
currentPlayer: 0
})
);
}
|
function add(uint256 _multiplier) public onlyOwner {
poolInfo.push(
PoolInfo({
Multiplier: _multiplier,
totalPoints: 0,
totalETH: 0,
totalplayer: 0,
currentPlayer: 0
})
);
}
| 1,595
|
296
|
// internal transfer function for virtual nfts/from address to move from/to address to move to/id id of nft to move
|
function _transferFrom(
address from,
address to,
uint256 id
|
function _transferFrom(
address from,
address to,
uint256 id
| 53,609
|
40
|
// Transfer tokens from ICO address to another address._to The address to transfer to._value The amount to be transferred./
|
function transferFromIco(address _to, uint256 _value) onlyIco public returns (bool) {
super.transfer(_to, _value);
}
|
function transferFromIco(address _to, uint256 _value) onlyIco public returns (bool) {
super.transfer(_to, _value);
}
| 42,427
|
59
|
// if update first element of array
|
if(index == 0 && tiers.length > 1) {
require(percent < tiers[1].percent, "Percent must be less than the next value");
require(amount < tiers[1].amount, "Amount must be less than the next value");
}
|
if(index == 0 && tiers.length > 1) {
require(percent < tiers[1].percent, "Percent must be less than the next value");
require(amount < tiers[1].amount, "Amount must be less than the next value");
}
| 19,111
|
10
|
// msg.sender.send(number) msg.sender.call.gas(0).value(number)();
|
if (msg.sender.call.gas(400000).value(shares[msg.sender])())
shares[msg.sender] = 0;
|
if (msg.sender.call.gas(400000).value(shares[msg.sender])())
shares[msg.sender] = 0;
| 16,839
|
12
|
// Allocation 11 / VestingType10, Ecosystem Total (20)% and Start After 92 days Locked the Token
|
vestingTypes.push(VestingType(782472613458529, 0, 92 days, 0, 0, true, true)); // 92 Days Locked, 0.0783085356303837 Percent daily for 1278 days
|
vestingTypes.push(VestingType(782472613458529, 0, 92 days, 0, 0, true, true)); // 92 Days Locked, 0.0783085356303837 Percent daily for 1278 days
| 4,276
|
34
|
// Op keys for Entropy storage
|
uint8 private constant UNSTAKE_AND_CLAIM_IDX = 0;
uint8 private constant CLAIM_IDX = 1;
|
uint8 private constant UNSTAKE_AND_CLAIM_IDX = 0;
uint8 private constant CLAIM_IDX = 1;
| 23,359
|
7
|
// Set new commission for collection bids in basis points /
|
function setCollectionCommission(uint newCollectionCommission) onlyOwner external {
if (newCollectionCommission > maxCommission) revert WrongCommission();
collectionCommission = newCollectionCommission;
}
|
function setCollectionCommission(uint newCollectionCommission) onlyOwner external {
if (newCollectionCommission > maxCommission) revert WrongCommission();
collectionCommission = newCollectionCommission;
}
| 27,893
|
110
|
// Transfer accrued credit surplus to another account/Can only transfer backed credit out of Aer/credit Amount of debt to settle [wad]
|
function transferCredit(address to, uint256 credit) external override checkCaller {
if (credit > sub(codex.credit(address(this)), codex.unbackedDebt(address(this))))
revert Aer__transferCredit_insufficientCredit();
codex.transferCredit(address(this), to, credit);
}
|
function transferCredit(address to, uint256 credit) external override checkCaller {
if (credit > sub(codex.credit(address(this)), codex.unbackedDebt(address(this))))
revert Aer__transferCredit_insufficientCredit();
codex.transferCredit(address(this), to, credit);
}
| 59,814
|
96
|
// check signer
|
require(signer == authorizedAddress, "authorized addresses must be equal");
|
require(signer == authorizedAddress, "authorized addresses must be equal");
| 36,606
|
70
|
// This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196.
|
uint public constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint public constant MAX_OPEN_FORCED_REQUESTS = 4096;
uint public constant MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE = 15 days;
uint public constant TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS = 7 days;
uint public constant MAX_NUM_ACCOUNTS = 2 ** 32;
uint public constant MAX_NUM_TOKENS = 2 ** 16;
uint public constant MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED = 7 days;
uint public constant MIN_TIME_IN_SHUTDOWN = 30 days;
|
uint public constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint public constant MAX_OPEN_FORCED_REQUESTS = 4096;
uint public constant MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE = 15 days;
uint public constant TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS = 7 days;
uint public constant MAX_NUM_ACCOUNTS = 2 ** 32;
uint public constant MAX_NUM_TOKENS = 2 ** 16;
uint public constant MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED = 7 days;
uint public constant MIN_TIME_IN_SHUTDOWN = 30 days;
| 3,473
|
149
|
// Reset function to restore initial state.TODO Remove /
|
function reset() external onlyGovernor {
_name = "Origin Dollar";
_symbol = "OUSD";
_decimals = 18;
rebasingCreditsPerToken = 1e18;
}
|
function reset() external onlyGovernor {
_name = "Origin Dollar";
_symbol = "OUSD";
_decimals = 18;
rebasingCreditsPerToken = 1e18;
}
| 18,777
|
67
|
// EIP-20 token name for this token
|
string public constant name = "k33pr.com";
|
string public constant name = "k33pr.com";
| 26,288
|
85
|
// User Accounting
|
UserTotals storage totals = _userTotals[msg.sender];
uint256 newUserStakingShareSeconds =
now
.sub(totals.lastAccountingTimestampSec)
.mul(totals.stakingShares);
totals.stakingShareSeconds =
totals.stakingShareSeconds
.add(newUserStakingShareSeconds);
totals.lastAccountingTimestampSec = now;
|
UserTotals storage totals = _userTotals[msg.sender];
uint256 newUserStakingShareSeconds =
now
.sub(totals.lastAccountingTimestampSec)
.mul(totals.stakingShares);
totals.stakingShareSeconds =
totals.stakingShareSeconds
.add(newUserStakingShareSeconds);
totals.lastAccountingTimestampSec = now;
| 30,409
|
23
|
// Returns to normal state. Requirements: - The contract must be paused. /
|
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
|
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
| 616
|
288
|
// Calculate the dy of withdrawing in one token self Swap struct to read from tokenIndex which token will be withdrawn tokenAmount the amount to withdraw in the pools precisionreturn the d and the new y after withdrawing one token /
|
function calculateWithdrawOneTokenDY(
Swap storage self,
uint8 tokenIndex,
uint256 tokenAmount
|
function calculateWithdrawOneTokenDY(
Swap storage self,
uint8 tokenIndex,
uint256 tokenAmount
| 8,800
|
45
|
// _allowances[owner][spender] = amount;
|
emit Approval(owner, spender, amount);
|
emit Approval(owner, spender, amount);
| 12,483
|
16
|
// function swap( address _tokenIn, address _tokenOut, uint _amountIn
|
// ) external {
// IERC20(_tokenIn).transferFrom(msg.sender, address(this), _amountIn);
// IERC20(_tokenIn).approve(UNISWAP_V2_ROUTER, _amountIn);
// address[] memory path;
// if (_tokenIn == WETH || _tokenOut == WETH) {
// path = new address[](2);
// path[0] = _tokenIn;
// path[1] = _tokenOut;
// } else {
// path = new address[](3);
// path[0] = _tokenIn;
// path[1] = WETH;
// path[2] = _tokenOut;
// }
// uint amountOut = getAmountOutMin(_tokenIn,_tokenOut, _amountIn);
// IUniswapV2Router(UNISWAP_V2_ROUTER).swapExactTokensForTokens(
// _amountIn,
// amountOut,
// path,
// address(this),
// block.timestamp +15
// );
// }
|
// ) external {
// IERC20(_tokenIn).transferFrom(msg.sender, address(this), _amountIn);
// IERC20(_tokenIn).approve(UNISWAP_V2_ROUTER, _amountIn);
// address[] memory path;
// if (_tokenIn == WETH || _tokenOut == WETH) {
// path = new address[](2);
// path[0] = _tokenIn;
// path[1] = _tokenOut;
// } else {
// path = new address[](3);
// path[0] = _tokenIn;
// path[1] = WETH;
// path[2] = _tokenOut;
// }
// uint amountOut = getAmountOutMin(_tokenIn,_tokenOut, _amountIn);
// IUniswapV2Router(UNISWAP_V2_ROUTER).swapExactTokensForTokens(
// _amountIn,
// amountOut,
// path,
// address(this),
// block.timestamp +15
// );
// }
| 23,628
|
270
|
// Get manager for permission_app Address of the app_role Identifier for a group of actions in app return address of the manager for the permission/
|
function getPermissionManager(address _app, bytes32 _role) public view returns (address) {
return permissionManager[roleHash(_app, _role)];
}
|
function getPermissionManager(address _app, bytes32 _role) public view returns (address) {
return permissionManager[roleHash(_app, _role)];
}
| 34,573
|
58
|
// handles when loaned token is different from what we borrowed
|
if (wasAvailable == false){
ERC20 loaned = ERC20(currentLToken);
convertEthToToken(0, address(this).balance, currentLToken);
performTrade(false, loaned.balanceOf(address(this)));
if (currentLToken == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2){
}
|
if (wasAvailable == false){
ERC20 loaned = ERC20(currentLToken);
convertEthToToken(0, address(this).balance, currentLToken);
performTrade(false, loaned.balanceOf(address(this)));
if (currentLToken == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2){
}
| 13,523
|
186
|
// To make etherscan auto-verify new pool, this variable is not immutable
|
bytes32 public domainSeparator;
|
bytes32 public domainSeparator;
| 28,048
|
25
|
// House takes a 1% fee (10/1000). Can be updated when game is stopped.Value is divided by 1000 instead of 100, to be able to use fractional percentages e.g., 1.5%
|
uint8 public houseFee = 10;
|
uint8 public houseFee = 10;
| 7,730
|
55
|
// Decodes unpadded base32 data of up to one word in length. self The data to decode. off Offset into the string to start at. len Number of characters to decode.return The decoded data, left aligned. /
|
function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) {
require(len <= 52);
uint ret = 0;
uint8 decoded;
for(uint i = 0; i < len; i++) {
bytes1 char = self[off + i];
require(char >= 0x30 && char <= 0x7A);
decoded = uint8(base32HexTable[uint(uint8(char)) - 0x30]);
require(decoded <= 0x20);
if(i == len - 1) {
break;
}
ret = (ret << 5) | decoded;
}
uint bitlen = len * 5;
if(len % 8 == 0) {
// Multiple of 8 characters, no padding
ret = (ret << 5) | decoded;
} else if(len % 8 == 2) {
// Two extra characters - 1 byte
ret = (ret << 3) | (decoded >> 2);
bitlen -= 2;
} else if(len % 8 == 4) {
// Four extra characters - 2 bytes
ret = (ret << 1) | (decoded >> 4);
bitlen -= 4;
} else if(len % 8 == 5) {
// Five extra characters - 3 bytes
ret = (ret << 4) | (decoded >> 1);
bitlen -= 1;
} else if(len % 8 == 7) {
// Seven extra characters - 4 bytes
ret = (ret << 2) | (decoded >> 3);
bitlen -= 3;
} else {
revert();
}
return bytes32(ret << (256 - bitlen));
}
|
function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) {
require(len <= 52);
uint ret = 0;
uint8 decoded;
for(uint i = 0; i < len; i++) {
bytes1 char = self[off + i];
require(char >= 0x30 && char <= 0x7A);
decoded = uint8(base32HexTable[uint(uint8(char)) - 0x30]);
require(decoded <= 0x20);
if(i == len - 1) {
break;
}
ret = (ret << 5) | decoded;
}
uint bitlen = len * 5;
if(len % 8 == 0) {
// Multiple of 8 characters, no padding
ret = (ret << 5) | decoded;
} else if(len % 8 == 2) {
// Two extra characters - 1 byte
ret = (ret << 3) | (decoded >> 2);
bitlen -= 2;
} else if(len % 8 == 4) {
// Four extra characters - 2 bytes
ret = (ret << 1) | (decoded >> 4);
bitlen -= 4;
} else if(len % 8 == 5) {
// Five extra characters - 3 bytes
ret = (ret << 4) | (decoded >> 1);
bitlen -= 1;
} else if(len % 8 == 7) {
// Seven extra characters - 4 bytes
ret = (ret << 2) | (decoded >> 3);
bitlen -= 3;
} else {
revert();
}
return bytes32(ret << (256 - bitlen));
}
| 16,913
|
134
|
// Allows the node operator to withdraw earned LINK to a given address The owner of the contract can be another wallet and does not have to be a Chainlink node recipient The address to send the LINK token to amount The amount to send (specified in wei) /
|
function withdraw(
address recipient,
uint256 amount
)
external
override(OracleInterface, WithdrawalInterface)
onlyOwner()
validateAvailableFunds(amount)
|
function withdraw(
address recipient,
uint256 amount
)
external
override(OracleInterface, WithdrawalInterface)
onlyOwner()
validateAvailableFunds(amount)
| 34,734
|
47
|
// Get the stake intent hash
|
bytes32 intentHash = hashStakeIntent(
_amount,
_beneficiary,
_staker,
_stakerNonce,
_gasPrice,
_gasLimit
);
|
bytes32 intentHash = hashStakeIntent(
_amount,
_beneficiary,
_staker,
_stakerNonce,
_gasPrice,
_gasLimit
);
| 14,768
|
65
|
// Approved rebaser for this contract /
|
address public rebaser;
|
address public rebaser;
| 5,022
|
37
|
// Destroys `amount` tokens from `account`, reducing the total supply.The caller must be an operator of `account`. If a send hook is registered for `account`, the corresponding functionwill be called with `data` and `operatorData`. See {IERC777Sender}. Emits a {Burned} event. Requirements - `account` cannot be the zero address.- `account` must have at least `amount` tokens.- the caller must be an operator for `account`. /
|
function operatorBurn(
|
function operatorBurn(
| 26,398
|
97
|
// do not allow to drain token if less than 30 days after farming
|
require(_token != bomb, "!bomb");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.token, "!pool.token");
}
|
require(_token != bomb, "!bomb");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.token, "!pool.token");
}
| 8,143
|
10
|
// swapExactInputSingle swaps a fixed amount of DAI for a maximum possible amount of WETH9/ using the DAI/WETH9 0.3% pool by calling `exactInputSingle` in the swap router./The calling address must approve this contract to spend at least `amountIn` worth of its DAI for this function to succeed./amountIn The exact amount of DAI that will be swapped for WETH9./ return amountOut The amount of WETH9 received.
|
function swapExactInputSingle(uint256 amountIn) external returns (uint256 amountOut) {
// msg.sender must approve this contract
// Transfer the specified amount of DAI to this contract.
TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn);
// Approve the router to spend DAI.
TransferHelper.safeApprove(DAI, address(swapRouter), amountIn);
// Naively set amountOutMinimum to 0. In production, use an oracle or other data source to choose a safer value for amountOutMinimum.
// We also set the sqrtPriceLimitx96 to be 0 to ensure we swap our exact input amount.
ISwapRouter.ExactInputSingleParams memory params =
ISwapRouter.ExactInputSingleParams({
tokenIn: DAI,
tokenOut: WETH9,
fee: poolFee,
recipient: msg.sender,
deadline: block.timestamp,
amountIn: amountIn,
amountOutMinimum: 0,
sqrtPriceLimitX96: 0
});
// The call to `exactInputSingle` executes the swap.
amountOut = swapRouter.exactInputSingle(params);
}
|
function swapExactInputSingle(uint256 amountIn) external returns (uint256 amountOut) {
// msg.sender must approve this contract
// Transfer the specified amount of DAI to this contract.
TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn);
// Approve the router to spend DAI.
TransferHelper.safeApprove(DAI, address(swapRouter), amountIn);
// Naively set amountOutMinimum to 0. In production, use an oracle or other data source to choose a safer value for amountOutMinimum.
// We also set the sqrtPriceLimitx96 to be 0 to ensure we swap our exact input amount.
ISwapRouter.ExactInputSingleParams memory params =
ISwapRouter.ExactInputSingleParams({
tokenIn: DAI,
tokenOut: WETH9,
fee: poolFee,
recipient: msg.sender,
deadline: block.timestamp,
amountIn: amountIn,
amountOutMinimum: 0,
sqrtPriceLimitX96: 0
});
// The call to `exactInputSingle` executes the swap.
amountOut = swapRouter.exactInputSingle(params);
}
| 46,055
|
346
|
// ERC721 Non-Fungible Token Standard basic implementation This is a modified OZ ERC721 base contract with one change where all tokens have the same token URI /
|
contract ERC721WithSameTokenURIForAllTokens is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Single token URI for all tokens
string public tokenURI_;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return tokenURI_;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @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(address from, address to, uint256 tokenId) internal virtual { }
}
|
contract ERC721WithSameTokenURIForAllTokens is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Single token URI for all tokens
string public tokenURI_;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return tokenURI_;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @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(address from, address to, uint256 tokenId) internal virtual { }
}
| 2,829
|
5
|
// Authorises a controller, who can register and renew domains.
|
function addController(address controller) external registrar_owner_only {
controllers[controller] = true;
emit ControllerAdded(controller);
}
|
function addController(address controller) external registrar_owner_only {
controllers[controller] = true;
emit ControllerAdded(controller);
}
| 42,619
|
30
|
// Modifier to make a function callable only if the reservation was paid. /
|
modifier whenPaid() {
require(paid);
_;
}
|
modifier whenPaid() {
require(paid);
_;
}
| 9,953
|
11
|
// Mint a given amount of shares & deduct the correct amount of assets to do so shares is the number of shares (vault tokens) receiver is the address of the receiver /
|
function mint(uint256 shares, address receiver) public onlyOwner returns (uint256) {
uint256 assets = convertToAssets(shares);
if (totalAssets() == 0) assets = shares;
ERC20(asset).safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
return assets;
}
|
function mint(uint256 shares, address receiver) public onlyOwner returns (uint256) {
uint256 assets = convertToAssets(shares);
if (totalAssets() == 0) assets = shares;
ERC20(asset).safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
return assets;
}
| 39,713
|
402
|
// Creates a new order _nftAddress - Non fungible registry address _assetId - ID of the published NFT _priceInWei - Price in Wei for the supported coin _expiresAt - Expiration time for the order /
|
function _createOrder(address _nftAddress, uint256 _assetId, uint256 _priceInWei,uint256 _royality, uint256 _expiresAt, address _currency) internal {
// Check nft registry
IERC721 nftRegistry = IERC721(_nftAddress);
// Check _acceptedCurrency
require(
acceptedCurrencies[_currency],
"Marketplace: Unacceptable marketplace currency"
);
// Check order creator is the asset owner
address assetOwner = nftRegistry.ownerOf(_assetId);
require(
assetOwner == msg.sender,
"Marketplace: Only the asset owner can create orders"
);
require(_priceInWei > 0, "Marketplace: Price should be bigger than 0");
require(
_expiresAt > block.timestamp.add(1 minutes),
"Marketplace: Publication should be more than 1 minute in the future"
);
// get NFT asset from seller
nftRegistry.safeTransferFrom(assetOwner, address(this), _assetId);
// create the orderId
bytes32 orderId = keccak256(abi.encodePacked(block.timestamp, assetOwner, _nftAddress, _assetId, _priceInWei));
// save order
orderByAssetId[_nftAddress][_assetId] = Order({
id: orderId,
seller: assetOwner,
nftAddress: _nftAddress,
price: _priceInWei,
royalty:_royality,
expiresAt: _expiresAt,
currency: _currency
});
emit OrderCreated(orderId, assetOwner, _nftAddress, _assetId, _priceInWei, _expiresAt, _currency);
}
|
function _createOrder(address _nftAddress, uint256 _assetId, uint256 _priceInWei,uint256 _royality, uint256 _expiresAt, address _currency) internal {
// Check nft registry
IERC721 nftRegistry = IERC721(_nftAddress);
// Check _acceptedCurrency
require(
acceptedCurrencies[_currency],
"Marketplace: Unacceptable marketplace currency"
);
// Check order creator is the asset owner
address assetOwner = nftRegistry.ownerOf(_assetId);
require(
assetOwner == msg.sender,
"Marketplace: Only the asset owner can create orders"
);
require(_priceInWei > 0, "Marketplace: Price should be bigger than 0");
require(
_expiresAt > block.timestamp.add(1 minutes),
"Marketplace: Publication should be more than 1 minute in the future"
);
// get NFT asset from seller
nftRegistry.safeTransferFrom(assetOwner, address(this), _assetId);
// create the orderId
bytes32 orderId = keccak256(abi.encodePacked(block.timestamp, assetOwner, _nftAddress, _assetId, _priceInWei));
// save order
orderByAssetId[_nftAddress][_assetId] = Order({
id: orderId,
seller: assetOwner,
nftAddress: _nftAddress,
price: _priceInWei,
royalty:_royality,
expiresAt: _expiresAt,
currency: _currency
});
emit OrderCreated(orderId, assetOwner, _nftAddress, _assetId, _priceInWei, _expiresAt, _currency);
}
| 81,579
|
23
|
// Make sure that every input is less than the snark scalar field
|
for (uint256 i = 0; i < input.length; i++) {
require(input[i] < SNARK_SCALAR_FIELD, "verifier-gte-snark-scalar-field");
vk_x = Pairing.plus(vk_x, Pairing.scalar_mul(vk.IC[i + 1], input[i]));
}
|
for (uint256 i = 0; i < input.length; i++) {
require(input[i] < SNARK_SCALAR_FIELD, "verifier-gte-snark-scalar-field");
vk_x = Pairing.plus(vk_x, Pairing.scalar_mul(vk.IC[i + 1], input[i]));
}
| 68,683
|
35
|
// Emitted when a claim was added. Specification: MUST be triggered when a claim was successfully added. /
|
event ClaimAdded(bytes32 indexed claimId, uint256 indexed topic, uint256 scheme, address indexed issuer, bytes signature, bytes data, string uri);
|
event ClaimAdded(bytes32 indexed claimId, uint256 indexed topic, uint256 scheme, address indexed issuer, bytes signature, bytes data, string uri);
| 55,810
|
3
|
// /
|
IJBTokenUriResolver public override tokenUriResolver;
|
IJBTokenUriResolver public override tokenUriResolver;
| 11,485
|
8
|
// Internal function that asserts the given `account` is in `_mintLimiters`.account The account address being queriedreturn True if the given `account` is in `_mintLimiters`, otherwise false /
|
function _isMintLimiter(address account) internal view returns (bool) {
return _mintLimiters.has(account);
}
|
function _isMintLimiter(address account) internal view returns (bool) {
return _mintLimiters.has(account);
}
| 8,680
|
2
|
// 0xF24294C0CF99c88452495D3e73c47a578402e317
|
address payable private constant _walletMarketing = payable(0x05825fFC6eA5fE6857f4AE3a7Ffc8ed045F402ec);
mapping (address => bool) private _noFees;
address private constant _swapRouterAddress = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Router02 private _primarySwapRouter = IUniswapV2Router02(_swapRouterAddress);
mapping (address => bool) private _isLP;
uint256 public startTime; // Reward Start Time
uint256 public weekTime; // Reward Weekly Time
|
address payable private constant _walletMarketing = payable(0x05825fFC6eA5fE6857f4AE3a7Ffc8ed045F402ec);
mapping (address => bool) private _noFees;
address private constant _swapRouterAddress = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Router02 private _primarySwapRouter = IUniswapV2Router02(_swapRouterAddress);
mapping (address => bool) private _isLP;
uint256 public startTime; // Reward Start Time
uint256 public weekTime; // Reward Weekly Time
| 24,111
|
43
|
// if zero requested, send the entire amount, otherwise the amount requested
|
uint256 _amount = _value > 0 ? _value : this.balance;
_beneficiary.transfer(_amount);
|
uint256 _amount = _value > 0 ? _value : this.balance;
_beneficiary.transfer(_amount);
| 60,459
|
48
|
// execution allowed only for contract owner
|
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
|
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
| 50,337
|
84
|
// Removes Curve LP and/or liquidity gauge tokens from the price feed/_derivatives Curve LP and/or liquidity gauge tokens to add
|
function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives");
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative");
require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set");
delete derivativeToInfo[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
|
function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives");
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative");
require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set");
delete derivativeToInfo[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
| 14,282
|
10
|
// this prevents dust from being added to the user account eg 10^18 -> 10^8 -> 10^18 will remove lower order bits
|
uint256 convertedWadAmount = LibReserve.tokenToWad(reserveTokenDecimals, amount);
|
uint256 convertedWadAmount = LibReserve.tokenToWad(reserveTokenDecimals, amount);
| 8,532
|
15
|
// Define a modifier that checks if airline has been already funded
|
modifier requireIsNotAlreadyFunded (address account)
|
modifier requireIsNotAlreadyFunded (address account)
| 50,843
|
42
|
// Check that this contract has a sufficient balance for the generation period
|
require(token.balanceOf(this) >= totalGenesisTokens);
started = true;
|
require(token.balanceOf(this) >= totalGenesisTokens);
started = true;
| 58,130
|
2
|
// True if increasing debt is forbidden
|
bool isIncreaseDebtForbidden;
|
bool isIncreaseDebtForbidden;
| 20,597
|
3
|
// toggle public sale
|
function changeStatePublicSale() public onlyOwner returns(bool) {
publicSaleState = !publicSaleState;
return publicSaleState;
}
|
function changeStatePublicSale() public onlyOwner returns(bool) {
publicSaleState = !publicSaleState;
return publicSaleState;
}
| 19,245
|
3
|
// NOTE: this is the "middle" period. Exit period for fresh utxos we'll double that while IFE phase is half that
|
uint256 public minExitPeriod;
address public operator;
uint256 public nextChildBlock;
uint256 public nextDepositBlock;
uint256 public nextFeeExit;
mapping (uint256 => Block) public blocks;
|
uint256 public minExitPeriod;
address public operator;
uint256 public nextChildBlock;
uint256 public nextDepositBlock;
uint256 public nextFeeExit;
mapping (uint256 => Block) public blocks;
| 26,676
|
48
|
// INVESTOR struct stores information about each Investor Investor can have more than one deals, but only one right to dispute
|
struct Investor {
bool disputing;
uint tokenAllowance;
uint etherUsed;
uint sumEther;
uint sumToken;
bool verdictForProject;
bool verdictForInvestor;
uint numberOfDeals;
}
|
struct Investor {
bool disputing;
uint tokenAllowance;
uint etherUsed;
uint sumEther;
uint sumToken;
bool verdictForProject;
bool verdictForInvestor;
uint numberOfDeals;
}
| 8,649
|
172
|
// 创建队伍至少需要投资1eth
|
require(_eth >= 1000000000000000000, "You need at least 1 eth to create a team, though creating a new team is free.");
|
require(_eth >= 1000000000000000000, "You need at least 1 eth to create a team, though creating a new team is free.");
| 67,456
|
196
|
// Reverts an expected payout./_projectId The ID of the project having paying out./_expectedDestination The address the payout was expected to go to./_allowanceAmount The amount that the destination has been allowed to use./_depositAmount The amount of the payout as debited from the project's balance.
|
function _revertTransferFrom(
uint256 _projectId,
address _expectedDestination,
uint256 _allowanceAmount,
uint256 _depositAmount
) internal {
|
function _revertTransferFrom(
uint256 _projectId,
address _expectedDestination,
uint256 _allowanceAmount,
uint256 _depositAmount
) internal {
| 30,286
|
171
|
// take gas cost at the beginning
|
_data.srcAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), _data.srcAmount, user, _gasCost, _data.srcAddr);
uint256 destAmount;
if (_data.destAddr != _data.srcAddr) {
_data.user = user;
_data.dfsFeeDivider = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
_data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE;
}
|
_data.srcAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), _data.srcAmount, user, _gasCost, _data.srcAddr);
uint256 destAmount;
if (_data.destAddr != _data.srcAddr) {
_data.user = user;
_data.dfsFeeDivider = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
_data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE;
}
| 2,640
|
346
|
// Calculates the minimum LP to accept when depositing underlying into Curve Pool. _hopLpAmount Amount of Hop LP that is being deposited into Curve Pool.return The minimum LP balance to accept. /
|
function _minLpAccepted(uint256 _hopLpAmount) internal view returns (uint256) {
return _hopLpToLp(_hopLpAmount).scaledMul(ScaledMath.ONE - imbalanceToleranceIn);
}
|
function _minLpAccepted(uint256 _hopLpAmount) internal view returns (uint256) {
return _hopLpToLp(_hopLpAmount).scaledMul(ScaledMath.ONE - imbalanceToleranceIn);
}
| 31,726
|
768
|
// Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`_kernel App's Kernel reference_appId Identifier for app_initializePayload Proxy initialization payload return AppProxyPinned/
|
function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) {
AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), false, _appId);
return proxy;
}
|
function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) {
AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), false, _appId);
return proxy;
}
| 5,945
|
8
|
// All other funds to be used per whitepaper guidelines
|
destinationAddress80 = 0xf030541A54e89cB22b3653a090b233A209E44F38;
|
destinationAddress80 = 0xf030541A54e89cB22b3653a090b233A209E44F38;
| 17,461
|
461
|
// current max tokenId
|
uint256 public tokenIdPointer;
|
uint256 public tokenIdPointer;
| 38,094
|
18
|
// 以下为ERC20的规范
|
constructor(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
|
constructor(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
| 23,605
|
2
|
// For locked indexers/delegations, this contract holds the mapping of L1 to L2 addresses
|
IL1GraphTokenLockTransferTool internal l1GraphTokenLockTransferTool;
|
IL1GraphTokenLockTransferTool internal l1GraphTokenLockTransferTool;
| 25,705
|
92
|
// Sets the closeFactor used when liquidating borrowsAdmin function to set closeFactornewCloseFactorMantissa New close factor, scaled by 1e18 return uint 0=success, otherwise a failure/
|
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
|
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
| 31,863
|
13
|
// - A function which calls internal _liquidate function to transfer any tokens left on the contract to investors after the endTime has passed investors - Array of investors addresses to liquidate /
|
function liquidate(address[] calldata investors) external {
require(block.timestamp >= endTime, 'The end time has not passed');
for (uint256 i = 0; i < investors.length; i++) {
address investor = investors[i];
uint256 availableTokens = userTotalAmount[investor];
uint256 claimedTokens = claimedAmount[investor];
require(
availableTokens != 0 && availableTokens != claimedTokens,
'no tokens to be distributed for an investor'
);
_liquidate(investor, availableTokens, claimedTokens);
}
}
|
function liquidate(address[] calldata investors) external {
require(block.timestamp >= endTime, 'The end time has not passed');
for (uint256 i = 0; i < investors.length; i++) {
address investor = investors[i];
uint256 availableTokens = userTotalAmount[investor];
uint256 claimedTokens = claimedAmount[investor];
require(
availableTokens != 0 && availableTokens != claimedTokens,
'no tokens to be distributed for an investor'
);
_liquidate(investor, availableTokens, claimedTokens);
}
}
| 21,764
|
3
|
// Revert with an error when attempting to withdrawal an amount greater than the current balance. /
|
error InvalidNativeTokenAmount(uint256 amount);
|
error InvalidNativeTokenAmount(uint256 amount);
| 17,513
|
9
|
// Update the given pool's token allocation point. Can only be called by the owner.
|
function set(
uint256 _poolId,
uint256 _tokenPerBlock,
bool _withUpdate
|
function set(
uint256 _poolId,
uint256 _tokenPerBlock,
bool _withUpdate
| 24,131
|
0
|
// Mock IDLE token
|
contract IDLEToken is ERC20("Idle", "IDLE") {
}
|
contract IDLEToken is ERC20("Idle", "IDLE") {
}
| 21,688
|
61
|
// amount of raised money in wei
|
uint public weiRaised;
|
uint public weiRaised;
| 5,739
|
14
|
// Burn tokens from an address _burnAmount The amount of tokens to burn /
|
function burn(uint _burnAmount) public {
require(_burnAmount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_burnAmount);
totalSupply = totalSupply.sub(_burnAmount);
emit Burned(msg.sender, _burnAmount);
}
|
function burn(uint _burnAmount) public {
require(_burnAmount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_burnAmount);
totalSupply = totalSupply.sub(_burnAmount);
emit Burned(msg.sender, _burnAmount);
}
| 52,335
|
64
|
// Single Tranfer
|
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
|
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
| 28,930
|
17
|
// Retrieve the offer.
|
OfferItem[] memory offer = orderParameters.offer;
|
OfferItem[] memory offer = orderParameters.offer;
| 14,955
|
22
|
// //Approve `to` to transfer up to `amount`./ return success Whether or not the approval succeeded.
|
function approve(address to, uint amount) external returns (bool success) {
allowance[msg.sender][to] = amount; /*adjust `allowance`*/
emit Approval(msg.sender, to, amount); /*emit event reflecting approval*/
success = true; /*confirm approval with ERC-20 accounting*/
}
|
function approve(address to, uint amount) external returns (bool success) {
allowance[msg.sender][to] = amount; /*adjust `allowance`*/
emit Approval(msg.sender, to, amount); /*emit event reflecting approval*/
success = true; /*confirm approval with ERC-20 accounting*/
}
| 12,615
|
28
|
// 获取补丁名称
|
function getPatchName(string ipfsHash) public constant returns (string) {
return patchMap[ipfsHash].name;
}
|
function getPatchName(string ipfsHash) public constant returns (string) {
return patchMap[ipfsHash].name;
}
| 9,196
|
121
|
// LP token for curve pool (ETH / stETH)
|
IERC20 private constant CURVE_LP =
IERC20(0x06325440D014e39736583c165C2963BA99fAf14E);
|
IERC20 private constant CURVE_LP =
IERC20(0x06325440D014e39736583c165C2963BA99fAf14E);
| 47,162
|
7
|
// Sets the merkle root. Only callable if the root is not yet set. _merkleRoot The merkle root to set. /
|
function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner {
require(merkleRoot == bytes32(0), "GasDao: Merkle root already set");
merkleRoot = _merkleRoot;
emit MerkleRootChanged(_merkleRoot);
}
|
function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner {
require(merkleRoot == bytes32(0), "GasDao: Merkle root already set");
merkleRoot = _merkleRoot;
emit MerkleRootChanged(_merkleRoot);
}
| 8,810
|
0
|
// injecter l'address du token Dai à utiliser
|
dai = IERC20(daiAddress);
|
dai = IERC20(daiAddress);
| 1,936
|
48
|
// For querying totalSupply of token/Required for ERC-721 compliance.
|
function totalSupply() public view returns (uint256 total) {
return citys.length;
}
|
function totalSupply() public view returns (uint256 total) {
return citys.length;
}
| 17,141
|
23
|
// Implements the use case: register Actor/Emits event to start the use case: ValidateID (access control)
|
function registerActor (address actorAddress_, uint40 prefix_, actorType actorRole_) public {
scActors[actorAddress_].companyPrefix=prefix_;
scActors[actorAddress_].actorAddress=msg.sender;
scActors[actorAddress_].actorRole=actorRole_;
scActors[actorAddress_].registered=true;
companyPrefixToactorAddress[prefix_]=msg.sender;
//Start the SCA certificate validation: import the ID and Certificates
emit importIDCertificate(actorAddress_, prefix_);
}
|
function registerActor (address actorAddress_, uint40 prefix_, actorType actorRole_) public {
scActors[actorAddress_].companyPrefix=prefix_;
scActors[actorAddress_].actorAddress=msg.sender;
scActors[actorAddress_].actorRole=actorRole_;
scActors[actorAddress_].registered=true;
companyPrefixToactorAddress[prefix_]=msg.sender;
//Start the SCA certificate validation: import the ID and Certificates
emit importIDCertificate(actorAddress_, prefix_);
}
| 15,003
|
18
|
// Atomically increases the allowance granted to `_spender` by the caller by `_addedValue`. This is an alternative to `approve` that can be used as a mitigation forproblems described in:Emits an `Approval` event indicating the updated allowance. Requirements: - `_spender` cannot be the the zero address.- the contract must not be paused. /
|
function increaseAllowance(
address _spender,
uint256 _addedValue
|
function increaseAllowance(
address _spender,
uint256 _addedValue
| 39,176
|
2
|
// Synonym of the uniswapV2's function, estimates amount you receive after swap.
|
function getAmountOut(uint256 amountA, address tokenA, address tokenB)
external
view
returns (uint256 amountOut);
|
function getAmountOut(uint256 amountA, address tokenA, address tokenB)
external
view
returns (uint256 amountOut);
| 34,389
|
131
|
// dcu出矿单位
|
uint128 _dcuUnit;
|
uint128 _dcuUnit;
| 55,894
|
9
|
// Return the ouput token address.return Output token address. /
|
function outputToken() external view override returns (IERC20Upgradeable) { return _outputToken; }
|
function outputToken() external view override returns (IERC20Upgradeable) { return _outputToken; }
| 14,968
|
57
|
// unstaking fee 0%
|
uint256 public unstakingFeeRate = 0;
|
uint256 public unstakingFeeRate = 0;
| 41,772
|
413
|
// The EIP-712 typehash for the ballot struct used by the contract
|
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
|
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
| 44,276
|
10
|
// Apply a StakeTransition._transition The disputed transition. _accountInfo The involved account from the previous transition. _stakingPoolInfo The involved staking pool from the previous transition. _globalInfo The involved global info from the previous transition.return new account, staking pool and global info after applying the disputed transition /
|
function applyStakeTransition(
dt.StakeTransition memory _transition,
dt.AccountInfo memory _accountInfo,
dt.StakingPoolInfo memory _stakingPoolInfo,
dt.GlobalInfo memory _globalInfo
)
external
pure
returns (
dt.AccountInfo memory,
|
function applyStakeTransition(
dt.StakeTransition memory _transition,
dt.AccountInfo memory _accountInfo,
dt.StakingPoolInfo memory _stakingPoolInfo,
dt.GlobalInfo memory _globalInfo
)
external
pure
returns (
dt.AccountInfo memory,
| 48,642
|
2
|
// People public person = People({favoriteNumber: 2, name: "Juan"});
|
function store (uint256 _favoriteNumber) public {
favoriteNumber = _favoriteNumber;
}
|
function store (uint256 _favoriteNumber) public {
favoriteNumber = _favoriteNumber;
}
| 23,392
|
4
|
// called by the owner to unpause the tokn, returns to normal state /
|
function unpause() public onlyOwner whenPaused {
boolStorage['paused'] = false;
Unpause();
}
|
function unpause() public onlyOwner whenPaused {
boolStorage['paused'] = false;
Unpause();
}
| 39,579
|
53
|
// return number of bytes until the data
|
function _payloadOffset(uint memPtr) private pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
|
function _payloadOffset(uint memPtr) private pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
| 40,050
|
5
|
// Update the Erc20Bank variable. _type The variable code. /
|
function updateErc20Bank(uint8 _type)
internal
|
function updateErc20Bank(uint8 _type)
internal
| 21,907
|
15
|
// ==== optional erc20 rescue function ===
|
function rescueERC20(
address _tokenAddress,
address _to,
uint256 _amount
|
function rescueERC20(
address _tokenAddress,
address _to,
uint256 _amount
| 27,769
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.