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 |
|---|---|---|---|---|
16 | // Set the name of the token name_ the new name of the token. / | function setName(string calldata name_) external onlyOwner {
_name = name_;
}
| function setName(string calldata name_) external onlyOwner {
_name = name_;
}
| 12,937 |
176 | // Sets the royalty information for a specific token id, overriding the global default. Requirements: - `tokenId` must be already minted.- `receiver` cannot be the zero address.- `feeNumerator` cannot be greater than the fee denominator. / | function _setTokenRoyalty(
uint256 tokenId,
address receiver,
uint96 feeNumerator
| function _setTokenRoyalty(
uint256 tokenId,
address receiver,
uint96 feeNumerator
| 16,033 |
138 | // case 2.2: R status changes to ONE | receiveQuote = backToOneReceiveQuote;
newRStatus = Types.RStatus.ONE;
| receiveQuote = backToOneReceiveQuote;
newRStatus = Types.RStatus.ONE;
| 1,918 |
4 | // List of events | mapping (uint => Event) public events;
uint public eventCount;
| mapping (uint => Event) public events;
uint public eventCount;
| 12,825 |
110 | // Provides the current CPI, as an 18 decimal fixed point number. | IDecentralizedOracle public cnyxPerUsdcOracle;
uint256 private constant DECIMALS = 18;
uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255);
uint256 public epoch;
uint256 public rebaseLag;
uint256 public deviationThreshold;
uint256 public rebaseWindowOffsetSec;
uint256 public rebaseWindowLengthSec;
| IDecentralizedOracle public cnyxPerUsdcOracle;
uint256 private constant DECIMALS = 18;
uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255);
uint256 public epoch;
uint256 public rebaseLag;
uint256 public deviationThreshold;
uint256 public rebaseWindowOffsetSec;
uint256 public rebaseWindowLengthSec;
| 18,123 |
175 | // The JELLY TOKEN! | JellyToken public jelly;
| JellyToken public jelly;
| 29,852 |
232 | // Function to swap ERC20 tokens for another ERC20 token using the UniswapV2Router02 tokenAmount The amount of ERC20 tokens to be swapped for another ERC20 tokenEffects:Approves the specified tokenAmount to be spent by the UniswapV2Router02 contractSwaps the specified tokenAmount of ERC20 tokens for another ERC20 token that has the erc20TokenFeeAddress / | function _swapTokensForTokens(uint256 tokenAmount) private {
address[] memory path = new address[](3);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
path[2] = address(erc20TokenFeeAddress);
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp + 3000
);
}
| function _swapTokensForTokens(uint256 tokenAmount) private {
address[] memory path = new address[](3);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
path[2] = address(erc20TokenFeeAddress);
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp + 3000
);
}
| 5,342 |
24 | // use this to update the registry address, if a wrong one was passed with the constructor | function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner(){
proxyRegistryAddress = _proxyRegistryAddress;
}
| function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner(){
proxyRegistryAddress = _proxyRegistryAddress;
}
| 29,517 |
226 | // stop everyone from 1. stop accepting more LP token into pool, 2. stop take any zapping 3. stop claim/harvest/zap rewarded cook 4. stop distributing cook reward | bool pauseMinig;
| bool pauseMinig;
| 31,750 |
19 | // Enables approved operators to burn tokens on behalf of their ownersFeature FEATURE_BURNS_ON_BEHALF must be enabled in order for `burn()` function to succeed when called by approved operator / | uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010;
| uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010;
| 49,970 |
12 | // Validate if the msg.sender owns the PublisherSubscription contract | modifier isSubscriptionOwner(address _addr) {
require(PublisherSubscription(_addr).subscriber() == msg.sender);
_;
}
| modifier isSubscriptionOwner(address _addr) {
require(PublisherSubscription(_addr).subscriber() == msg.sender);
_;
}
| 4,435 |
0 | // Emits when a deposit is made.Addresses are represented with bytes32 to maximize compatibility withnon-Ethereum-compatible blockchains.srcChainId Chain ID of the source blockchain (current chain) destChainId Chain ID of the destination blockchain depositId Unique ID of the deposit on the current chain depositor Address of the account on the current chain that made the deposit recipient Address of the account on the destination chain that will receive the amount currency A bytes32-encoded universal currency key amount Amount of tokens being deposited to recipient's address. / | event TokenDeposited(
uint256 srcChainId,
uint256 destChainId,
uint256 depositId,
bytes32 depositor,
bytes32 recipient,
bytes32 currency,
uint256 amount
);
event TokenWithdrawn(
| event TokenDeposited(
uint256 srcChainId,
uint256 destChainId,
uint256 depositId,
bytes32 depositor,
bytes32 recipient,
bytes32 currency,
uint256 amount
);
event TokenWithdrawn(
| 44,485 |
30 | // add account to allow calling of transferIXT allowedAddress Address of account/ | function setAllowed(address allowedAddress) public ownerOnly {
allowed[allowedAddress] = true;
}
| function setAllowed(address allowedAddress) public ownerOnly {
allowed[allowedAddress] = true;
}
| 51,365 |
43 | // compute corrected FRAC so we generate round number of bonus capital, subtr 1 so we never overflow | correctedBonusFrac = Math.proportion(maximumBonusOptions + r, DECIMAL_POWER, BONUS_OPTIONS_FRAC) - 1;
| correctedBonusFrac = Math.proportion(maximumBonusOptions + r, DECIMAL_POWER, BONUS_OPTIONS_FRAC) - 1;
| 16,541 |
219 | // Claim Verb for all Kinesis tokens owned by the sender | function claimAllForOwner() external {
require(
active, "Project not active!"
);
require(
kinesisClaimingOpen, "Kinesis claiming is closed!"
);
uint256 tokenBalanceOwner = kinesisContract.balanceOf(_msgSender());
// Checks
require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED");
uint256 tokenId;
for (uint256 i = 0; i < tokenBalanceOwner; i++) {
tokenId = kinesisContract.tokenOfOwnerByIndex(_msgSender(), i);
require(
!tokenIdClaimed[tokenId],
"TOKEN_ALREADY_CLAIMED"
);
tokenIdClaimed[tokenId] = true;
_claim(_msgSender());
}
}
| function claimAllForOwner() external {
require(
active, "Project not active!"
);
require(
kinesisClaimingOpen, "Kinesis claiming is closed!"
);
uint256 tokenBalanceOwner = kinesisContract.balanceOf(_msgSender());
// Checks
require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED");
uint256 tokenId;
for (uint256 i = 0; i < tokenBalanceOwner; i++) {
tokenId = kinesisContract.tokenOfOwnerByIndex(_msgSender(), i);
require(
!tokenIdClaimed[tokenId],
"TOKEN_ALREADY_CLAIMED"
);
tokenIdClaimed[tokenId] = true;
_claim(_msgSender());
}
}
| 45,172 |
3 | // Storing each word costs about 20,000 gas, so 100,000 is a safe default for this example contract. | uint32 s_callbackGasLimit = 500000;
| uint32 s_callbackGasLimit = 500000;
| 81,926 |
48 | // Call the transfer function | require(token.transfer(msg.sender, stakeAmount), "Unable to transfer token back to the account");
| require(token.transfer(msg.sender, stakeAmount), "Unable to transfer token back to the account");
| 5,427 |
71 | // Gets the Sum Assured Amount of a given cover. | function getCoverSumAssured(uint _cid) external view returns (uint sa) {
sa = allCovers[_cid].sumAssured;
}
| function getCoverSumAssured(uint _cid) external view returns (uint sa) {
sa = allCovers[_cid].sumAssured;
}
| 28,436 |
1 | // Request ID: | uint64 public arrngRequestId;
| uint64 public arrngRequestId;
| 10,082 |
19 | // overflow should be impossible in for-loop index cache accounts length to save gas | uint256 loopLength = accounts.length - 1;
for (uint256 i = 0; i < loopLength; ++i) {
| uint256 loopLength = accounts.length - 1;
for (uint256 i = 0; i < loopLength; ++i) {
| 12,195 |
85 | // Utilities for Sheet Fighter | library SheetFighterUtilities {
/// @notice Substring string on range [_startIndex, _endIndex)
/// @param _str String to substring
/// @param _startIndex Start index, inclusive
/// @param _endIndex End index, exclusive
/// @return Substring from range [_startIndex, endIndex)
function substring(string memory _str, uint256 _startIndex, uint256 _endIndex) internal pure returns(string memory) {
bytes memory _strBytes = bytes(_str);
bytes memory _substringBytes = new bytes(_endIndex - _startIndex);
uint256 strIndex = 0;
for(uint256 i = _startIndex; i < _endIndex; i++) {
_substringBytes[strIndex] = _strBytes[i];
strIndex++;
}
return string(_substringBytes);
}
/// @notice Split a flavor text string, deliminated by a pipe ("|"), with four partitions
/// @dev This function does NOT test for edge cases, like consecutive pipes, or strings ending with a pipe
/// @param _str String to split, deliminated by a pipe: "|"
/// @return A list of strings, resulting from spliting _str
function splitFlavorTextString(string memory _str) internal pure returns(string[5] memory) {
bytes memory str = bytes(_str);
uint256 startIndex = 0;
uint partitionIndex = 0;
// Array to hold partitions
string[5] memory strArr;
for(uint256 i = 0; i < str.length; i++) {
if(str[i] == "|") {
// Save partition
strArr[partitionIndex] = substring(_str, startIndex, i);
// Continue to next partition
startIndex = i + 1;
partitionIndex += 1;
}
}
// Save last partition
strArr[4] = substring(_str, startIndex, str.length);
return strArr;
}
/// @dev Get a bit mask
/// @param _numBits Number of bits to use for the max
/// @return A bit mask to be used with the bit-wise operator &
function getBitMask(uint256 _numBits) internal pure returns(uint256) {
return (2 << (_numBits + 1)) - 1;
}
/// @notice Get fighter stat
/// @param _stats Stats for the fighter
/// @param _shiftBits Number of bits to shift to get to the stat
/// @param _min Min value for the stat
/// @param _max Max value for the stat
/// @return The stat, bounded by _min and _max
function getFighterStat(
uint256 _stats,
uint8 _shiftBits,
uint8 _min,
uint8 _max
)
internal
pure
returns(uint8)
{
uint256 bitMask = 0xFF; // Equivalent to 11111111 in binary
uint256 rangeWidth = _max - _min;
// Get the stat unnormalized (i.e. not bounded between _min and _max)
uint8 statUnnormalized = uint8((_stats >> _shiftBits) & bitMask);
// Get the stat normalized (i.e. bounded between _min and _max, inclusive)
uint8 statNormalized = (uint8(statUnnormalized % (rangeWidth + 1))) + _min;
return statNormalized;
}
}
| library SheetFighterUtilities {
/// @notice Substring string on range [_startIndex, _endIndex)
/// @param _str String to substring
/// @param _startIndex Start index, inclusive
/// @param _endIndex End index, exclusive
/// @return Substring from range [_startIndex, endIndex)
function substring(string memory _str, uint256 _startIndex, uint256 _endIndex) internal pure returns(string memory) {
bytes memory _strBytes = bytes(_str);
bytes memory _substringBytes = new bytes(_endIndex - _startIndex);
uint256 strIndex = 0;
for(uint256 i = _startIndex; i < _endIndex; i++) {
_substringBytes[strIndex] = _strBytes[i];
strIndex++;
}
return string(_substringBytes);
}
/// @notice Split a flavor text string, deliminated by a pipe ("|"), with four partitions
/// @dev This function does NOT test for edge cases, like consecutive pipes, or strings ending with a pipe
/// @param _str String to split, deliminated by a pipe: "|"
/// @return A list of strings, resulting from spliting _str
function splitFlavorTextString(string memory _str) internal pure returns(string[5] memory) {
bytes memory str = bytes(_str);
uint256 startIndex = 0;
uint partitionIndex = 0;
// Array to hold partitions
string[5] memory strArr;
for(uint256 i = 0; i < str.length; i++) {
if(str[i] == "|") {
// Save partition
strArr[partitionIndex] = substring(_str, startIndex, i);
// Continue to next partition
startIndex = i + 1;
partitionIndex += 1;
}
}
// Save last partition
strArr[4] = substring(_str, startIndex, str.length);
return strArr;
}
/// @dev Get a bit mask
/// @param _numBits Number of bits to use for the max
/// @return A bit mask to be used with the bit-wise operator &
function getBitMask(uint256 _numBits) internal pure returns(uint256) {
return (2 << (_numBits + 1)) - 1;
}
/// @notice Get fighter stat
/// @param _stats Stats for the fighter
/// @param _shiftBits Number of bits to shift to get to the stat
/// @param _min Min value for the stat
/// @param _max Max value for the stat
/// @return The stat, bounded by _min and _max
function getFighterStat(
uint256 _stats,
uint8 _shiftBits,
uint8 _min,
uint8 _max
)
internal
pure
returns(uint8)
{
uint256 bitMask = 0xFF; // Equivalent to 11111111 in binary
uint256 rangeWidth = _max - _min;
// Get the stat unnormalized (i.e. not bounded between _min and _max)
uint8 statUnnormalized = uint8((_stats >> _shiftBits) & bitMask);
// Get the stat normalized (i.e. bounded between _min and _max, inclusive)
uint8 statNormalized = (uint8(statUnnormalized % (rangeWidth + 1))) + _min;
return statNormalized;
}
}
| 40,434 |
302 | // First fill: validate order and permit maker asset | _validate(order.makerAssetData, order.takerAssetData, signature, orderHash);
remainingMakerAmount = order.makerAssetData.decodeUint256(_AMOUNT_INDEX);
if (order.permit.length > 0) {
(address token, bytes memory permit) = abi.decode(order.permit, (address, bytes));
token.uncheckedFunctionCall(abi.encodePacked(IERC20Permit.permit.selector, permit), "LOP: permit failed");
require(_remaining[orderHash] == 0, "LOP: reentrancy detected");
}
| _validate(order.makerAssetData, order.takerAssetData, signature, orderHash);
remainingMakerAmount = order.makerAssetData.decodeUint256(_AMOUNT_INDEX);
if (order.permit.length > 0) {
(address token, bytes memory permit) = abi.decode(order.permit, (address, bytes));
token.uncheckedFunctionCall(abi.encodePacked(IERC20Permit.permit.selector, permit), "LOP: permit failed");
require(_remaining[orderHash] == 0, "LOP: reentrancy detected");
}
| 39,429 |
19 | // Reclaim all ERC20Basic compatible tokens _token ERC20Basic The address of the token contract / | function reclaimToken(IERC20 _token) external onlyOwner {
uint256 balance = _token.balanceOf(address(this));
_token.safeTransfer(owner(), balance);
}
| function reclaimToken(IERC20 _token) external onlyOwner {
uint256 balance = _token.balanceOf(address(this));
_token.safeTransfer(owner(), balance);
}
| 20,841 |
4 | // SelfCallableOwnable allows either owner or the contract itself to call its functions/providing an additional modifier to check if Owner or self is calling/the "self" here is used for the meta transactions | contract SelfCallableOwnable is Ownable {
/// @dev Check if the sender is the Owner or self
modifier onlyOwnerOrSelf() {
require(_isOwner(msg.sender) || msg.sender == address(this), "only owner||self");
_;
}
}
| contract SelfCallableOwnable is Ownable {
/// @dev Check if the sender is the Owner or self
modifier onlyOwnerOrSelf() {
require(_isOwner(msg.sender) || msg.sender == address(this), "only owner||self");
_;
}
}
| 35,265 |
32 | // developers and user run this to take funds | require(_launchpadId <= totalLaunchpads, "Invalid launchpadId");
require(launchpads[_launchpadId].paid == false, "This launchpad has been settled");
| require(_launchpadId <= totalLaunchpads, "Invalid launchpadId");
require(launchpads[_launchpadId].paid == false, "This launchpad has been settled");
| 7,471 |
45 | // Emitted when an asset rate is settled | event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate);
| event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate);
| 15,785 |
76 | // Returns the integer division of two unsigned integers, reverting with custom message ondivision by zero. The result is rounded towards zero. Counterpart to Solidity's `%` operator. This function uses a `revert`opcode (which leaves remaining gas untouched) while Solidity uses aninvalid opcode to revert (consuming all remaining gas). Counterpart to Solidity's `/` operator. Note: this function uses a`revert` opcode (which leaves remaining gas untouched) while Solidityuses an invalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero. / | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
| function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
| 1,720 |
5 | // TODO: JUST FOR DEBUGGGGG!!! | return (yesResults > votesSum/2) && (votesSum>1);
| return (yesResults > votesSum/2) && (votesSum>1);
| 26,970 |
44 | // Return true if G2 point is on the curve. / | function isG2PointOnCurve(G2Point memory point) internal pure returns(bool) {
(uint256 y2x, uint256 y2y) = _gfP2Square(point.y.x, point.y.y);
(uint256 x3x, uint256 x3y) = _gfP2CubeAddTwistB(point.x.x, point.x.y);
return (y2x == x3x && y2y == x3y);
}
| function isG2PointOnCurve(G2Point memory point) internal pure returns(bool) {
(uint256 y2x, uint256 y2y) = _gfP2Square(point.y.x, point.y.y);
(uint256 x3x, uint256 x3y) = _gfP2CubeAddTwistB(point.x.x, point.x.y);
return (y2x == x3x && y2y == x3y);
}
| 7,877 |
9 | // loop through the leaderboard | for (uint i=0; i<leaderboardLength; i++) {
| for (uint i=0; i<leaderboardLength; i++) {
| 26,350 |
9 | // Has the value of minimum collateral qty required | uint256 public minimumCollateralQty;
| uint256 public minimumCollateralQty;
| 20,312 |
42 | // If the given _weekCursor is behind block.timestamp We take _slopeDelta from the recorded slopeChanges We can use _weekCursor directly because key of slopeChanges is timestamp round off to week | _slopeDelta = slopeChanges[_weekCursor];
| _slopeDelta = slopeChanges[_weekCursor];
| 41,367 |
205 | // Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller / | function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
| function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
| 9,897 |
10 | // Governance only function for setting maximum daily DOLA supply delta allowed for the fed newMaxDailyDelta The new maximum amount underlyingSupply can be expanded or contracted in a day/ | function setMaxDailyDelta(uint newMaxDailyDelta) external onlyGov {
maxDailyDelta = newMaxDailyDelta;
}
| function setMaxDailyDelta(uint newMaxDailyDelta) external onlyGov {
maxDailyDelta = newMaxDailyDelta;
}
| 25,135 |
0 | // increase spend amount granted to spender spender address whose allowance to increase amount quantity by which to increase allowancereturn success status (always true; otherwise function will revert) / | function increaseAllowance(address spender, uint256 amount)
public
virtual
returns (bool)
{
unchecked {
mapping(address => uint256) storage allowances = ERC20BaseStorage
.layout()
.allowances[msg.sender];
| function increaseAllowance(address spender, uint256 amount)
public
virtual
returns (bool)
{
unchecked {
mapping(address => uint256) storage allowances = ERC20BaseStorage
.layout()
.allowances[msg.sender];
| 19,657 |
463 | // if(!securityOff)require(msg.sender == ord.user ||msg.sender == keeper ||msg.sender == owner(), "wrong user or keeper"); | IUniswapV3Pool _pool = IUniswapV3Pool(ord.pool);
(uint256 _amount0, uint256 _amount1) =
_pool.burn(ord.tickLower, ord.tickUpper, ord.liquidity);
_pool.collect(address(this), ord.tickLower, ord.tickUpper,
uint128(_amount0), uint128(_amount1));
| IUniswapV3Pool _pool = IUniswapV3Pool(ord.pool);
(uint256 _amount0, uint256 _amount1) =
_pool.burn(ord.tickLower, ord.tickUpper, ord.liquidity);
_pool.collect(address(this), ord.tickLower, ord.tickUpper,
uint128(_amount0), uint128(_amount1));
| 66,442 |
97 | // This is representing % of every asset on the contract Example: 32% is safety threshold | safetyThreshold = _safetyThreshold;
emit SafetyThresholdChanged(_safetyThreshold);
| safetyThreshold = _safetyThreshold;
emit SafetyThresholdChanged(_safetyThreshold);
| 80,509 |
33 | // Get the updated Element Merkle Root, given an Append Proof and elements to append | function get_new_root_from_append_proof_multi_append(bytes[] calldata append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
| function get_new_root_from_append_proof_multi_append(bytes[] calldata append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
| 52,089 |
152 | // params | function getPeriod() public view returns (uint256) {
return period;
}
| function getPeriod() public view returns (uint256) {
return period;
}
| 14,715 |
341 | // Market Open Interest. If we're finalized we need actually calculate the value | if (_market.isFinalized()) {
for (uint8 i = 0; i < _numOutcomes; i++) {
_expectedBalance = _expectedBalance.add(totalSupplyForMarketOutcome(_market, i).mul(_market.getWinningPayoutNumerator(i)));
}
| if (_market.isFinalized()) {
for (uint8 i = 0; i < _numOutcomes; i++) {
_expectedBalance = _expectedBalance.add(totalSupplyForMarketOutcome(_market, i).mul(_market.getWinningPayoutNumerator(i)));
}
| 12,902 |
4 | // Dev fee | uint16 public DEVP = 500;
| uint16 public DEVP = 500;
| 36,214 |
103 | // mapping for token URIs |
mapping (uint256 => string) private _tokenURIs;
|
mapping (uint256 => string) private _tokenURIs;
| 3,154 |
34 | // Appends a byte to the end of the buffer. Resizes if doing so would exceed the capacity of the buffer.buf The buffer to append to.data The data to append. return The original buffer./ | function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
return writeInt(buf, buf.buf.length, data, len);
}
| function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
return writeInt(buf, buf.buf.length, data, len);
}
| 46,009 |
3 | // Sale info/The contract address of the nft | address nftContract;
| address nftContract;
| 10,095 |
48 | // Return the usd value of UniswapV2 pair. mutilpled by 1e18/We only consider the value without ALD./_pair The address of UniswapV2 pair./_amount The amount of asset/ | function value(address _pair, uint256 _amount) external view override returns (uint256) {
uint256 _price = price(_pair);
return _price.mul(_amount).div(10**IERC20Metadata(_pair).decimals());
}
| function value(address _pair, uint256 _amount) external view override returns (uint256) {
uint256 _price = price(_pair);
return _price.mul(_amount).div(10**IERC20Metadata(_pair).decimals());
}
| 9,903 |
111 | // Address of the KeeperDAO borrow proxy. This will be the/ `msg.sender` for calls to the `helloCallback` function. | address public borrowProxy;
| address public borrowProxy;
| 4,122 |
117 | // scale value and return a new decimal | return Decimal(FixidityLib.newFixed(value, decimals), significant);
| return Decimal(FixidityLib.newFixed(value, decimals), significant);
| 23,777 |
52 | // Transfer a token between 2 addresses letting the receiver knows of the transfer from The send of the token to The recipient of the token id The id of the token / | function safeTransferFrom(address from, address to, uint256 id) external {
safeTransferFrom(from, to, id, "");
}
| function safeTransferFrom(address from, address to, uint256 id) external {
safeTransferFrom(from, to, id, "");
}
| 18,497 |
164 | // Same as DVM | IDODOCallee(to).DVMSellShareCall(
msg.sender,
shareAmount,
baseAmount,
quoteAmount,
data
);
| IDODOCallee(to).DVMSellShareCall(
msg.sender,
shareAmount,
baseAmount,
quoteAmount,
data
);
| 66,831 |
19 | // 2. memory arrays these arrays are not stored inside the blockchain. | function bar() external {
uint256[] memory newArray = new uint256[](10);
newArray[0] = 10;
newArray[1] = 20;
newArray[0];
delete newArray[5];
}
| function bar() external {
uint256[] memory newArray = new uint256[](10);
newArray[0] = 10;
newArray[1] = 20;
newArray[0];
delete newArray[5];
}
| 43,220 |
36 | // require(stakingToken.transfer(owner, UNSTAKE_FEE),"Not enough tokens in contract!"); |
require(
stakingToken.transfer(msg.sender, withAmount),
"Not enough tokens in contract!"
);
delete stakes[msg.sender];
removeStakeholder(msg.sender);
emit Unstaked(msg.sender, withdrawAmount);
|
require(
stakingToken.transfer(msg.sender, withAmount),
"Not enough tokens in contract!"
);
delete stakes[msg.sender];
removeStakeholder(msg.sender);
emit Unstaked(msg.sender, withdrawAmount);
| 40,432 |
0 | // The Moonbeam Team/The interface through which solidity contracts will interact with Relay Encoder/ We follow this same interface including four-byte function selectors, in the precompile that/ wraps the pallet | interface IRelayEncoder {
// dev Encode 'bond' relay call
// Selector: 31627376
// @param controller_address: Address of the controller
// @param amount: The amount to bond
// @param reward_destination: the account that should receive the reward
// @returns The bytes associated with the encoded call
function encode_bond(uint256 controller_address, uint256 amount, bytes memory reward_destination) external view returns (bytes memory result);
// dev Encode 'bond_extra' relay call
// Selector: 49def326
// @param amount: The extra amount to bond
// @returns The bytes associated with the encoded call
function encode_bond_extra(uint256 amount) external view returns (bytes memory result);
// dev Encode 'unbond' relay call
// Selector: bc4b2187
// @param amount: The amount to unbond
// @returns The bytes associated with the encoded call
function encode_unbond(uint256 amount) external view returns (bytes memory result);
// dev Encode 'withdraw_unbonded' relay call
// Selector: 2d220331
// @param slashes: Weight hint, number of slashing spans
// @returns The bytes associated with the encoded call
function encode_withdraw_unbonded(uint32 slashes) external view returns (bytes memory result);
// dev Encode 'validate' relay call
// Selector: 3a0d803a
// @param comission: Comission of the validator as parts_per_billion
// @param blocked: Whether or not the validator is accepting more nominations
// @returns The bytes associated with the encoded call
// selector: 3a0d803a
// function encode_validate(uint256 comission, bool blocked) external pure returns (bytes memory result);
// dev Encode 'nominate' relay call
// Selector: a7cb124b
// @param nominees: An array of AccountIds corresponding to the accounts we will nominate
// @param blocked: Whether or not the validator is accepting more nominations
// @returns The bytes associated with the encoded call
function encode_nominate(uint256 [] memory nominees) external view returns (bytes memory result);
// dev Encode 'chill' relay call
// Selector: bc4b2187
// @returns The bytes associated with the encoded call
function encode_chill() external view returns (bytes memory result);
// dev Encode 'set_payee' relay call
// Selector: 9801b147
// @param reward_destination: the account that should receive the reward
// @returns The bytes associated with the encoded call
// function encode_set_payee(bytes memory reward_destination) external pure returns (bytes memory result);
// dev Encode 'set_controller' relay call
// Selector: 7a8f48c2
// @param controller: The controller address
// @returns The bytes associated with the encoded call
// function encode_set_controller(uint256 controller) external pure returns (bytes memory result);
// dev Encode 'rebond' relay call
// Selector: add6b3bf
// @param amount: The amount to rebond
// @returns The bytes associated with the encoded call
function encode_rebond(uint256 amount) external view returns (bytes memory result);
}
| interface IRelayEncoder {
// dev Encode 'bond' relay call
// Selector: 31627376
// @param controller_address: Address of the controller
// @param amount: The amount to bond
// @param reward_destination: the account that should receive the reward
// @returns The bytes associated with the encoded call
function encode_bond(uint256 controller_address, uint256 amount, bytes memory reward_destination) external view returns (bytes memory result);
// dev Encode 'bond_extra' relay call
// Selector: 49def326
// @param amount: The extra amount to bond
// @returns The bytes associated with the encoded call
function encode_bond_extra(uint256 amount) external view returns (bytes memory result);
// dev Encode 'unbond' relay call
// Selector: bc4b2187
// @param amount: The amount to unbond
// @returns The bytes associated with the encoded call
function encode_unbond(uint256 amount) external view returns (bytes memory result);
// dev Encode 'withdraw_unbonded' relay call
// Selector: 2d220331
// @param slashes: Weight hint, number of slashing spans
// @returns The bytes associated with the encoded call
function encode_withdraw_unbonded(uint32 slashes) external view returns (bytes memory result);
// dev Encode 'validate' relay call
// Selector: 3a0d803a
// @param comission: Comission of the validator as parts_per_billion
// @param blocked: Whether or not the validator is accepting more nominations
// @returns The bytes associated with the encoded call
// selector: 3a0d803a
// function encode_validate(uint256 comission, bool blocked) external pure returns (bytes memory result);
// dev Encode 'nominate' relay call
// Selector: a7cb124b
// @param nominees: An array of AccountIds corresponding to the accounts we will nominate
// @param blocked: Whether or not the validator is accepting more nominations
// @returns The bytes associated with the encoded call
function encode_nominate(uint256 [] memory nominees) external view returns (bytes memory result);
// dev Encode 'chill' relay call
// Selector: bc4b2187
// @returns The bytes associated with the encoded call
function encode_chill() external view returns (bytes memory result);
// dev Encode 'set_payee' relay call
// Selector: 9801b147
// @param reward_destination: the account that should receive the reward
// @returns The bytes associated with the encoded call
// function encode_set_payee(bytes memory reward_destination) external pure returns (bytes memory result);
// dev Encode 'set_controller' relay call
// Selector: 7a8f48c2
// @param controller: The controller address
// @returns The bytes associated with the encoded call
// function encode_set_controller(uint256 controller) external pure returns (bytes memory result);
// dev Encode 'rebond' relay call
// Selector: add6b3bf
// @param amount: The amount to rebond
// @returns The bytes associated with the encoded call
function encode_rebond(uint256 amount) external view returns (bytes memory result);
}
| 3,188 |
17 | // name of the pool | string calldata name,
| string calldata name,
| 15,939 |
96 | // in case of withdraw, we have 2 branches: 1. the user withdraws less than he added in the current epoch 2. the user withdraws more than he added in the current epoch (including 0) | if (amount < currentEpochCheckpoint.newDeposits) {
uint128 avgDepositMultiplier = uint128(
balanceBefore.sub(currentEpochCheckpoint.startBalance).mul(BASE_MULTIPLIER).div(currentEpochCheckpoint.newDeposits)
);
currentEpochCheckpoint.newDeposits = currentEpochCheckpoint.newDeposits.sub(amount);
currentEpochCheckpoint.multiplier = computeNewMultiplier(
currentEpochCheckpoint.startBalance,
BASE_MULTIPLIER,
| if (amount < currentEpochCheckpoint.newDeposits) {
uint128 avgDepositMultiplier = uint128(
balanceBefore.sub(currentEpochCheckpoint.startBalance).mul(BASE_MULTIPLIER).div(currentEpochCheckpoint.newDeposits)
);
currentEpochCheckpoint.newDeposits = currentEpochCheckpoint.newDeposits.sub(amount);
currentEpochCheckpoint.multiplier = computeNewMultiplier(
currentEpochCheckpoint.startBalance,
BASE_MULTIPLIER,
| 37,608 |
24 | // Allows an owner to confirm a transaction. / | function confirmTransaction(
uint256 tokenId,
uint256 transactionId
)
public
requireIsValidOwnerAndCouncilIsSetUp(tokenId)
transactionExists(transactionId)
notConfirmed(transactionId, tokenId)
| function confirmTransaction(
uint256 tokenId,
uint256 transactionId
)
public
requireIsValidOwnerAndCouncilIsSetUp(tokenId)
transactionExists(transactionId)
notConfirmed(transactionId, tokenId)
| 76,105 |
78 | // when buy | if (_marketPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
if(_OPEN_BLOCK_ + 1 >= block.number){
_blackList[to] = true;
}
| if (_marketPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
if(_OPEN_BLOCK_ + 1 >= block.number){
_blackList[to] = true;
}
| 79,070 |
23 | // Order can not be canceled if the book has alredy been sent | require(!sent);
| require(!sent);
| 55,320 |
6 | // Returns the index of the most significant bit of x/x The value as a uint256/ return msb The index of the most significant bit of x | function mostSignificantBit(uint256 x) internal pure returns (uint8 msb) {
unchecked {
if (x >= 1 << 128) {
x >>= 128;
msb = 128;
}
if (x >= 1 << 64) {
x >>= 64;
msb += 64;
}
if (x >= 1 << 32) {
x >>= 32;
msb += 32;
}
if (x >= 1 << 16) {
x >>= 16;
msb += 16;
}
if (x >= 1 << 8) {
x >>= 8;
msb += 8;
}
if (x >= 1 << 4) {
x >>= 4;
msb += 4;
}
if (x >= 1 << 2) {
x >>= 2;
msb += 2;
}
if (x >= 1 << 1) {
msb += 1;
}
}
}
| function mostSignificantBit(uint256 x) internal pure returns (uint8 msb) {
unchecked {
if (x >= 1 << 128) {
x >>= 128;
msb = 128;
}
if (x >= 1 << 64) {
x >>= 64;
msb += 64;
}
if (x >= 1 << 32) {
x >>= 32;
msb += 32;
}
if (x >= 1 << 16) {
x >>= 16;
msb += 16;
}
if (x >= 1 << 8) {
x >>= 8;
msb += 8;
}
if (x >= 1 << 4) {
x >>= 4;
msb += 4;
}
if (x >= 1 << 2) {
x >>= 2;
msb += 2;
}
if (x >= 1 << 1) {
msb += 1;
}
}
}
| 23,518 |
56 | // assetID to Start Time of Current Trip | mapping(uint32 => uint32) public assetIdCurrentTripStartTimeMapping;
| mapping(uint32 => uint32) public assetIdCurrentTripStartTimeMapping;
| 30,587 |
147 | // Process multiple output orders/_nftId The id of the NFT to update/_batchedOrders The order to execute | function processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders) external;
| function processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders) external;
| 62,684 |
421 | // Deployer for Fem governance contracts and FemErecter.Deploys governance in an unusable state, then activates thecontracts once the sale is successful. / | contract GovernessActivator {
TimelockController public immutable timelockController;
Governess public immutable governess;
IFem public immutable fem;
FemErecter public immutable femErecter;
constructor(
address _fem,
address _devAddress,
uint256 _devTokenBips,
uint32 _saleStartTime,
uint32 _saleDuration,
uint32 _timeToSpend,
uint256 _minimumEthRaised
) {
fem = IFem(_fem);
Governess _governess = new Governess(_fem, address(this), type(uint256).max);
governess = _governess;
address[] memory proposers = new address[](1);
address[] memory executors = new address[](1);
proposers[0] = address(_governess);
executors[0] = address(_governess);
TimelockController timelock = new TimelockController(2 days, proposers, executors);
timelockController = timelock;
timelockController.renounceRole(keccak256('TIMELOCK_ADMIN_ROLE'), address(this));
femErecter = new FemErecter(
address(timelock),
_devAddress,
_devTokenBips,
_fem,
_saleStartTime,
_saleDuration,
_timeToSpend,
_minimumEthRaised
);
}
function activateGoverness() external {
require(
femErecter.state() == IFemErecter.SaleState.FUNDS_PENDING,
'Can not activate governess before sale succeeds'
);
uint256 finalSupply = (fem.totalSupply() * (10000 + femErecter.devTokenBips())) / 10000;
uint256 proposalThreshold = finalSupply / 100;
governess.setProposalThreshold(proposalThreshold);
governess.updateTimelock(timelockController);
}
}
| contract GovernessActivator {
TimelockController public immutable timelockController;
Governess public immutable governess;
IFem public immutable fem;
FemErecter public immutable femErecter;
constructor(
address _fem,
address _devAddress,
uint256 _devTokenBips,
uint32 _saleStartTime,
uint32 _saleDuration,
uint32 _timeToSpend,
uint256 _minimumEthRaised
) {
fem = IFem(_fem);
Governess _governess = new Governess(_fem, address(this), type(uint256).max);
governess = _governess;
address[] memory proposers = new address[](1);
address[] memory executors = new address[](1);
proposers[0] = address(_governess);
executors[0] = address(_governess);
TimelockController timelock = new TimelockController(2 days, proposers, executors);
timelockController = timelock;
timelockController.renounceRole(keccak256('TIMELOCK_ADMIN_ROLE'), address(this));
femErecter = new FemErecter(
address(timelock),
_devAddress,
_devTokenBips,
_fem,
_saleStartTime,
_saleDuration,
_timeToSpend,
_minimumEthRaised
);
}
function activateGoverness() external {
require(
femErecter.state() == IFemErecter.SaleState.FUNDS_PENDING,
'Can not activate governess before sale succeeds'
);
uint256 finalSupply = (fem.totalSupply() * (10000 + femErecter.devTokenBips())) / 10000;
uint256 proposalThreshold = finalSupply / 100;
governess.setProposalThreshold(proposalThreshold);
governess.updateTimelock(timelockController);
}
}
| 32,671 |
58 | // require artist to have configured price of token on this minter | require(_projectConfig.priceIsConfigured, "Price not configured");
| require(_projectConfig.priceIsConfigured, "Price not configured");
| 30,804 |
83 | // exclude from fees, wallet limit and transaction limit | excludeFromAllLimits(owner(), true);
excludeFromAllLimits(address(this), true);
excludeFromWalletLimit(uniswapV2Pair, true);
dev = _dev;
| excludeFromAllLimits(owner(), true);
excludeFromAllLimits(address(this), true);
excludeFromWalletLimit(uniswapV2Pair, true);
dev = _dev;
| 21,861 |
94 | // Base URI for computing {tokenURI}. If set, the resulting URI for eachtoken will be the concatenation of the `baseURI` and the `tokenId`. Emptyby default, can be overriden in child contracts. / | function _baseURI() internal view virtual returns (string memory) {
| function _baseURI() internal view virtual returns (string memory) {
| 22,496 |
32 | // Checks if given address corresponds to a registered and funded airline / | function isFundedAirline
(
address airline
)
external
view
requireIsOperational
requireIsCallerAuthorized
returns (bool)
| function isFundedAirline
(
address airline
)
external
view
requireIsOperational
requireIsCallerAuthorized
returns (bool)
| 49,604 |
66 | // A mapping of token ID to price paid for the token | mapping(uint256 => uint256) pricePaid;
| mapping(uint256 => uint256) pricePaid;
| 21,248 |
524 | // inital price of the token sale | ITokenPrice.TokenPriceData initialPrice;
PaymentType paymentType; // the type of payment that is being used
address tokenAddress; // the address of the payment token, if payment type is TOKEN
| ITokenPrice.TokenPriceData initialPrice;
PaymentType paymentType; // the type of payment that is being used
address tokenAddress; // the address of the payment token, if payment type is TOKEN
| 76,054 |
17 | // update the current bid amount and the bidder address | auction.currentPrice = uint128(_bidAmount);
auction.buyer = msg.sender;
| auction.currentPrice = uint128(_bidAmount);
auction.buyer = msg.sender;
| 19,314 |
23 | // Delete the slot where the moved value was stored | set._values.pop();
| set._values.pop();
| 28,116 |
143 | // Only owner and directTransferer can invoke withdrawals | (_operator == owner() || _operator == directTransferer) &&
| (_operator == owner() || _operator == directTransferer) &&
| 21,090 |
73 | // test | bool inSwapAndLiquifyOne;
| bool inSwapAndLiquifyOne;
| 18,824 |
338 | // Calcs user share depending on deposited amounts | function _calcShare(uint128 liquidity, uint128 liquidityLast)
internal
view
returns (
uint256 shares
)
| function _calcShare(uint128 liquidity, uint128 liquidityLast)
internal
view
returns (
uint256 shares
)
| 2,969 |
10 | // event indicates voting round status is now 'Active' / | event LogVoteStarted();
| event LogVoteStarted();
| 17,810 |
1 | // =============/collection => permits disabled, permits are enabled by default | mapping(address => bool) internal _disablePermits;
| mapping(address => bool) internal _disablePermits;
| 4,174 |
40 | // Many of the settings that change weekly rely on the rate accumulator described at https:docs.makerdao.com/smart-contract-modules/rates-module To check this yourself, use the following rate calculation (example 8%): $ bc -l <<< 'scale=27; e( l(1.08)/(606024365) )' A table of rates can be found athttps:ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW | uint256 constant ZERO_PERCENT_RATE = 1000000000000000000000000000;
uint256 constant ONE_PERCENT_RATE = 1000000000315522921573372069;
uint256 constant TWO_PERCENT_RATE = 1000000000627937192491029810;
uint256 constant TWO_POINT_FIVE_PERCENT_RATE = 1000000000782997609082909351;
uint256 constant THREE_PERCENT_RATE = 1000000000937303470807876289;
uint256 constant FOUR_POINT_FIVE_PERCENT_RATE = 1000000001395766281313196627;
uint256 constant FIVE_PERCENT_RATE = 1000000001547125957863212448;
uint256 constant SIX_PERCENT_RATE = 1000000001847694957439350562;
uint256 constant EIGHT_PERCENT_RATE = 1000000002440418608258400030;
uint256 constant NINE_PERCENT_RATE = 1000000002732676825177582095;
| uint256 constant ZERO_PERCENT_RATE = 1000000000000000000000000000;
uint256 constant ONE_PERCENT_RATE = 1000000000315522921573372069;
uint256 constant TWO_PERCENT_RATE = 1000000000627937192491029810;
uint256 constant TWO_POINT_FIVE_PERCENT_RATE = 1000000000782997609082909351;
uint256 constant THREE_PERCENT_RATE = 1000000000937303470807876289;
uint256 constant FOUR_POINT_FIVE_PERCENT_RATE = 1000000001395766281313196627;
uint256 constant FIVE_PERCENT_RATE = 1000000001547125957863212448;
uint256 constant SIX_PERCENT_RATE = 1000000001847694957439350562;
uint256 constant EIGHT_PERCENT_RATE = 1000000002440418608258400030;
uint256 constant NINE_PERCENT_RATE = 1000000002732676825177582095;
| 36,194 |
78 | // Team wallet | _feeAddrWallet1 = payable(0x12f558F6fCB48550a4aC5388F675CC8aC2B08C32);
| _feeAddrWallet1 = payable(0x12f558F6fCB48550a4aC5388F675CC8aC2B08C32);
| 9,771 |
45 | // Returns the memory pointer one word after `mPtr`. | function next(
MemoryPointer mPtr
| function next(
MemoryPointer mPtr
| 33,442 |
4 | // Transmission records the median answer from the transmit transaction at time timestamp | struct Transmission {
int192 answer; // 192 bits ought to be enough for anyone
uint64 timestamp;
}
| struct Transmission {
int192 answer; // 192 bits ought to be enough for anyone
uint64 timestamp;
}
| 6,610 |
22 | // Send the percentage of funds to a shareholder´s wallet / | function _withdraw(address payable _account, uint256 _amount) internal {
(bool sent, ) = _account.call{value: _amount}("");
require(sent, "Failed to send Ether");
}
| function _withdraw(address payable _account, uint256 _amount) internal {
(bool sent, ) = _account.call{value: _amount}("");
require(sent, "Failed to send Ether");
}
| 11,457 |
6 | // Address of the immutable rain script deployed as a `VMState`. | address private vmStatePointer;
| address private vmStatePointer;
| 20,981 |
144 | // HonestMfer earn 10000 $COIN per day | uint public constant DAILY_COIN_RATE = 10000 ether;
uint public constant MINIMUM_TIME_TO_EXIT = 2 days;
uint public constant TAX_PERCENTAGE = 20;
uint public constant MAXIMUM_GLOBAL_COIN = 2400000000 ether;
uint public totalCoinEarned;
uint public lastClaimTimestamp;
uint public thiefReward = 0;
| uint public constant DAILY_COIN_RATE = 10000 ether;
uint public constant MINIMUM_TIME_TO_EXIT = 2 days;
uint public constant TAX_PERCENTAGE = 20;
uint public constant MAXIMUM_GLOBAL_COIN = 2400000000 ether;
uint public totalCoinEarned;
uint public lastClaimTimestamp;
uint public thiefReward = 0;
| 27,398 |
81 | // Check for approved spend | if (_from != msg.sender) {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value;
}
| if (_from != msg.sender) {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value;
}
| 36,005 |
487 | // the previous stored state must be overwritten with the latest output. |
function getIndex(uint256 range, bytes32 state)
internal
view
returns (uint256, bytes32)
|
function getIndex(uint256 range, bytes32 state)
internal
view
returns (uint256, bytes32)
| 5,046 |
7 | // _price: in drace token_val: true => open for sale_val: false => cancel sale, return token to owner | function setTokenSale(uint256 _tokenId, uint256 _price) external {
require(_price > 0, "price must not be 0");
//transfer token from sender to contract
nft.transferFrom(msg.sender, address(this), _tokenId);
//create a sale
saleList.push(SaleInfo(
false,
true,
msg.sender,
block.timestamp,
_tokenId,
_price,
saleList.length
));
emit NewTokenSale(msg.sender, block.timestamp, _tokenId, _price, saleList.length - 1);
}
| function setTokenSale(uint256 _tokenId, uint256 _price) external {
require(_price > 0, "price must not be 0");
//transfer token from sender to contract
nft.transferFrom(msg.sender, address(this), _tokenId);
//create a sale
saleList.push(SaleInfo(
false,
true,
msg.sender,
block.timestamp,
_tokenId,
_price,
saleList.length
));
emit NewTokenSale(msg.sender, block.timestamp, _tokenId, _price, saleList.length - 1);
}
| 6,486 |
3 | // fallback function invests in fundraiser fee percentage is given to owner for providing this service remainder is invested in fundraiser | function() payable {
uint issuedTokens = msg.value * (100 - issueFeePercent) / 100;
// pay fee to owner
if(!owner.send(msg.value - issuedTokens))
throw;
// invest remainder into fundraiser
if(!fundraiserAddress.call.value(issuedTokens)(fundraiserCallData))
throw;
// issue tokens by increasing total supply and balance
totalSupply += issuedTokens;
balances[msg.sender] += issuedTokens;
}
| function() payable {
uint issuedTokens = msg.value * (100 - issueFeePercent) / 100;
// pay fee to owner
if(!owner.send(msg.value - issuedTokens))
throw;
// invest remainder into fundraiser
if(!fundraiserAddress.call.value(issuedTokens)(fundraiserCallData))
throw;
// issue tokens by increasing total supply and balance
totalSupply += issuedTokens;
balances[msg.sender] += issuedTokens;
}
| 34,547 |
5 | // check on the current number of bank types deployed / | function bankCount() external view returns (uint256) {
return banks.length;
}
| function bankCount() external view returns (uint256) {
return banks.length;
}
| 4,221 |
19 | // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // solhint-disable reason-string / | interface IEntryPoint is IStakeManager {
/***
* An event emitted after each successful request
* @param userOpHash - unique identifier for the request (hash its entire content, except signature).
* @param sender - the account that generates this request.
* @param paymaster - if non-null, the paymaster that pays for this request.
* @param nonce - the nonce value from the request.
* @param success - true if the sender transaction succeeded, false if reverted.
* @param actualGasCost - actual amount paid (by account or paymaster) for this UserOperation.
* @param actualGasUsed - total gas used by this UserOperation (including preVerification, creation, validation and execution).
*/
event UserOperationEvent(
bytes32 indexed userOpHash,
address indexed sender,
address indexed paymaster,
uint256 nonce,
bool success,
uint256 actualGasCost,
uint256 actualGasUsed
);
/**
* account "sender" was deployed.
* @param userOpHash the userOp that deployed this account. UserOperationEvent will follow.
* @param sender the account that is deployed
* @param factory the factory used to deploy this account (in the initCode)
* @param paymaster the paymaster used by this UserOp
*/
event AccountDeployed(bytes32 indexed userOpHash, address indexed sender, address factory, address paymaster);
/**
* An event emitted if the UserOperation "callData" reverted with non-zero length
* @param userOpHash the request unique identifier.
* @param sender the sender of this request
* @param nonce the nonce used in the request
* @param revertReason - the return bytes from the (reverted) call to "callData".
*/
event UserOperationRevertReason(
bytes32 indexed userOpHash,
address indexed sender,
uint256 nonce,
bytes revertReason
);
/**
* signature aggregator used by the following UserOperationEvents within this bundle.
*/
event SignatureAggregatorChanged(address indexed aggregator);
/**
* a custom revert error of handleOps, to identify the offending op.
* NOTE: if simulateValidation passes successfully, there should be no reason for handleOps to fail on it.
* @param opIndex - index into the array of ops to the failed one (in simulateValidation, this is always zero)
* @param reason - revert reason
* The string starts with a unique code "AAmn", where "m" is "1" for factory, "2" for account and "3" for paymaster issues,
* so a failure can be attributed to the correct entity.
* Should be caught in off-chain handleOps simulation and not happen on-chain.
* Useful for mitigating DoS attempts against batchers or for troubleshooting of factory/account/paymaster reverts.
*/
error FailedOp(uint256 opIndex, string reason);
/**
* error case when a signature aggregator fails to verify the aggregated signature it had created.
*/
error SignatureValidationFailed(address aggregator);
/**
* Successful result from simulateValidation.
* @param returnInfo gas and time-range returned values
* @param senderInfo stake information about the sender
* @param factoryInfo stake information about the factory (if any)
* @param paymasterInfo stake information about the paymaster (if any)
*/
error ValidationResult(ReturnInfo returnInfo, StakeInfo senderInfo, StakeInfo factoryInfo, StakeInfo paymasterInfo);
/**
* Successful result from simulateValidation, if the account returns a signature aggregator
* @param returnInfo gas and time-range returned values
* @param senderInfo stake information about the sender
* @param factoryInfo stake information about the factory (if any)
* @param paymasterInfo stake information about the paymaster (if any)
* @param aggregatorInfo signature aggregation info (if the account requires signature aggregator)
* bundler MUST use it to verify the signature, or reject the UserOperation
*/
error ValidationResultWithAggregation(
ReturnInfo returnInfo,
StakeInfo senderInfo,
StakeInfo factoryInfo,
StakeInfo paymasterInfo,
AggregatorStakeInfo aggregatorInfo
);
/**
* return value of getSenderAddress
*/
error SenderAddressResult(address sender);
/**
* return value of simulateHandleOp
*/
error ExecutionResult(
uint256 preOpGas,
uint256 paid,
uint48 validAfter,
uint48 validUntil,
bool targetSuccess,
bytes targetResult
);
//UserOps handled, per aggregator
struct UserOpsPerAggregator {
UserOperation[] userOps;
// aggregator address
IAggregator aggregator;
// aggregated signature
bytes signature;
}
/**
* Execute a batch of UserOperation.
* no signature aggregator is used.
* if any account requires an aggregator (that is, it returned an aggregator when
* performing simulateValidation), then handleAggregatedOps() must be used instead.
* @param ops the operations to execute
* @param beneficiary the address to receive the fees
*/
function handleOps(UserOperation[] calldata ops, address payable beneficiary) external;
/**
* Execute a batch of UserOperation with Aggregators
* @param opsPerAggregator the operations to execute, grouped by aggregator (or address(0) for no-aggregator accounts)
* @param beneficiary the address to receive the fees
*/
function handleAggregatedOps(UserOpsPerAggregator[] calldata opsPerAggregator, address payable beneficiary)
external;
/**
* generate a request Id - unique identifier for this request.
* the request ID is a hash over the content of the userOp (except the signature), the entrypoint and the chainid.
*/
function getUserOpHash(UserOperation calldata userOp) external view returns (bytes32);
/**
* Simulate a call to account.validateUserOp and paymaster.validatePaymasterUserOp.
* @dev this method always revert. Successful result is ValidationResult error. other errors are failures.
* @dev The node must also verify it doesn't use banned opcodes, and that it doesn't reference storage outside the account's data.
* @param userOp the user operation to validate.
*/
function simulateValidation(UserOperation calldata userOp) external;
/**
* gas and return values during simulation
* @param preOpGas the gas used for validation (including preValidationGas)
* @param prefund the required prefund for this operation
* @param sigFailed validateUserOp's (or paymaster's) signature check failed
* @param validAfter - first timestamp this UserOp is valid (merging account and paymaster time-range)
* @param validUntil - last timestamp this UserOp is valid (merging account and paymaster time-range)
* @param paymasterContext returned by validatePaymasterUserOp (to be passed into postOp)
*/
struct ReturnInfo {
uint256 preOpGas;
uint256 prefund;
bool sigFailed;
uint48 validAfter;
uint48 validUntil;
bytes paymasterContext;
}
/**
* returned aggregated signature info.
* the aggregator returned by the account, and its current stake.
*/
struct AggregatorStakeInfo {
address aggregator;
StakeInfo stakeInfo;
}
/**
* Get counterfactual sender address.
* Calculate the sender contract address that will be generated by the initCode and salt in the UserOperation.
* this method always revert, and returns the address in SenderAddressResult error
* @param initCode the constructor code to be passed into the UserOperation.
*/
function getSenderAddress(bytes memory initCode) external;
/**
* simulate full execution of a UserOperation (including both validation and target execution)
* this method will always revert with "ExecutionResult".
* it performs full validation of the UserOperation, but ignores signature error.
* an optional target address is called after the userop succeeds, and its value is returned
* (before the entire call is reverted)
* Note that in order to collect the the success/failure of the target call, it must be executed
* with trace enabled to track the emitted events.
* @param op the UserOperation to simulate
* @param target if nonzero, a target address to call after userop simulation. If called, the targetSuccess and targetResult
* are set to the return from that call.
* @param targetCallData callData to pass to target address
*/
function simulateHandleOp(
UserOperation calldata op,
address target,
bytes calldata targetCallData
) external;
}
| interface IEntryPoint is IStakeManager {
/***
* An event emitted after each successful request
* @param userOpHash - unique identifier for the request (hash its entire content, except signature).
* @param sender - the account that generates this request.
* @param paymaster - if non-null, the paymaster that pays for this request.
* @param nonce - the nonce value from the request.
* @param success - true if the sender transaction succeeded, false if reverted.
* @param actualGasCost - actual amount paid (by account or paymaster) for this UserOperation.
* @param actualGasUsed - total gas used by this UserOperation (including preVerification, creation, validation and execution).
*/
event UserOperationEvent(
bytes32 indexed userOpHash,
address indexed sender,
address indexed paymaster,
uint256 nonce,
bool success,
uint256 actualGasCost,
uint256 actualGasUsed
);
/**
* account "sender" was deployed.
* @param userOpHash the userOp that deployed this account. UserOperationEvent will follow.
* @param sender the account that is deployed
* @param factory the factory used to deploy this account (in the initCode)
* @param paymaster the paymaster used by this UserOp
*/
event AccountDeployed(bytes32 indexed userOpHash, address indexed sender, address factory, address paymaster);
/**
* An event emitted if the UserOperation "callData" reverted with non-zero length
* @param userOpHash the request unique identifier.
* @param sender the sender of this request
* @param nonce the nonce used in the request
* @param revertReason - the return bytes from the (reverted) call to "callData".
*/
event UserOperationRevertReason(
bytes32 indexed userOpHash,
address indexed sender,
uint256 nonce,
bytes revertReason
);
/**
* signature aggregator used by the following UserOperationEvents within this bundle.
*/
event SignatureAggregatorChanged(address indexed aggregator);
/**
* a custom revert error of handleOps, to identify the offending op.
* NOTE: if simulateValidation passes successfully, there should be no reason for handleOps to fail on it.
* @param opIndex - index into the array of ops to the failed one (in simulateValidation, this is always zero)
* @param reason - revert reason
* The string starts with a unique code "AAmn", where "m" is "1" for factory, "2" for account and "3" for paymaster issues,
* so a failure can be attributed to the correct entity.
* Should be caught in off-chain handleOps simulation and not happen on-chain.
* Useful for mitigating DoS attempts against batchers or for troubleshooting of factory/account/paymaster reverts.
*/
error FailedOp(uint256 opIndex, string reason);
/**
* error case when a signature aggregator fails to verify the aggregated signature it had created.
*/
error SignatureValidationFailed(address aggregator);
/**
* Successful result from simulateValidation.
* @param returnInfo gas and time-range returned values
* @param senderInfo stake information about the sender
* @param factoryInfo stake information about the factory (if any)
* @param paymasterInfo stake information about the paymaster (if any)
*/
error ValidationResult(ReturnInfo returnInfo, StakeInfo senderInfo, StakeInfo factoryInfo, StakeInfo paymasterInfo);
/**
* Successful result from simulateValidation, if the account returns a signature aggregator
* @param returnInfo gas and time-range returned values
* @param senderInfo stake information about the sender
* @param factoryInfo stake information about the factory (if any)
* @param paymasterInfo stake information about the paymaster (if any)
* @param aggregatorInfo signature aggregation info (if the account requires signature aggregator)
* bundler MUST use it to verify the signature, or reject the UserOperation
*/
error ValidationResultWithAggregation(
ReturnInfo returnInfo,
StakeInfo senderInfo,
StakeInfo factoryInfo,
StakeInfo paymasterInfo,
AggregatorStakeInfo aggregatorInfo
);
/**
* return value of getSenderAddress
*/
error SenderAddressResult(address sender);
/**
* return value of simulateHandleOp
*/
error ExecutionResult(
uint256 preOpGas,
uint256 paid,
uint48 validAfter,
uint48 validUntil,
bool targetSuccess,
bytes targetResult
);
//UserOps handled, per aggregator
struct UserOpsPerAggregator {
UserOperation[] userOps;
// aggregator address
IAggregator aggregator;
// aggregated signature
bytes signature;
}
/**
* Execute a batch of UserOperation.
* no signature aggregator is used.
* if any account requires an aggregator (that is, it returned an aggregator when
* performing simulateValidation), then handleAggregatedOps() must be used instead.
* @param ops the operations to execute
* @param beneficiary the address to receive the fees
*/
function handleOps(UserOperation[] calldata ops, address payable beneficiary) external;
/**
* Execute a batch of UserOperation with Aggregators
* @param opsPerAggregator the operations to execute, grouped by aggregator (or address(0) for no-aggregator accounts)
* @param beneficiary the address to receive the fees
*/
function handleAggregatedOps(UserOpsPerAggregator[] calldata opsPerAggregator, address payable beneficiary)
external;
/**
* generate a request Id - unique identifier for this request.
* the request ID is a hash over the content of the userOp (except the signature), the entrypoint and the chainid.
*/
function getUserOpHash(UserOperation calldata userOp) external view returns (bytes32);
/**
* Simulate a call to account.validateUserOp and paymaster.validatePaymasterUserOp.
* @dev this method always revert. Successful result is ValidationResult error. other errors are failures.
* @dev The node must also verify it doesn't use banned opcodes, and that it doesn't reference storage outside the account's data.
* @param userOp the user operation to validate.
*/
function simulateValidation(UserOperation calldata userOp) external;
/**
* gas and return values during simulation
* @param preOpGas the gas used for validation (including preValidationGas)
* @param prefund the required prefund for this operation
* @param sigFailed validateUserOp's (or paymaster's) signature check failed
* @param validAfter - first timestamp this UserOp is valid (merging account and paymaster time-range)
* @param validUntil - last timestamp this UserOp is valid (merging account and paymaster time-range)
* @param paymasterContext returned by validatePaymasterUserOp (to be passed into postOp)
*/
struct ReturnInfo {
uint256 preOpGas;
uint256 prefund;
bool sigFailed;
uint48 validAfter;
uint48 validUntil;
bytes paymasterContext;
}
/**
* returned aggregated signature info.
* the aggregator returned by the account, and its current stake.
*/
struct AggregatorStakeInfo {
address aggregator;
StakeInfo stakeInfo;
}
/**
* Get counterfactual sender address.
* Calculate the sender contract address that will be generated by the initCode and salt in the UserOperation.
* this method always revert, and returns the address in SenderAddressResult error
* @param initCode the constructor code to be passed into the UserOperation.
*/
function getSenderAddress(bytes memory initCode) external;
/**
* simulate full execution of a UserOperation (including both validation and target execution)
* this method will always revert with "ExecutionResult".
* it performs full validation of the UserOperation, but ignores signature error.
* an optional target address is called after the userop succeeds, and its value is returned
* (before the entire call is reverted)
* Note that in order to collect the the success/failure of the target call, it must be executed
* with trace enabled to track the emitted events.
* @param op the UserOperation to simulate
* @param target if nonzero, a target address to call after userop simulation. If called, the targetSuccess and targetResult
* are set to the return from that call.
* @param targetCallData callData to pass to target address
*/
function simulateHandleOp(
UserOperation calldata op,
address target,
bytes calldata targetCallData
) external;
}
| 2,676 |
0 | // All the swaps | mapping (bytes32 => Swap) public swaps;
| mapping (bytes32 => Swap) public swaps;
| 19,056 |
75 | // Stake shares Longer Pays Better bonus constants used by _stakeStartBonusSuns() /uint256 private constant LPB_BONUS_PERCENT = 20;uint256 private constant LPB_BONUS_MAX_PERCENT = 200; | uint256 internal constant LPB = (18 * 100) / 20; /* LPB_BONUS_PERCENT */
uint256 internal constant LPB_MAX_DAYS = (LPB * 200) / 100; /* LPB_BONUS_MAX_PERCENT */
| uint256 internal constant LPB = (18 * 100) / 20; /* LPB_BONUS_PERCENT */
uint256 internal constant LPB_MAX_DAYS = (LPB * 200) / 100; /* LPB_BONUS_MAX_PERCENT */
| 47,396 |
28 | // Emit an event for the token sale | emit TokensSold(msg.sender, _amount, receivedBNB);
| emit TokensSold(msg.sender, _amount, receivedBNB);
| 25,297 |
54 | // Returns the token id given a token's address/_tokenAddress The address of the token to target/ return _tokenId The id of the token | function tokenId(address _tokenAddress) external view returns (uint256 _tokenId);
| function tokenId(address _tokenAddress) external view returns (uint256 _tokenId);
| 28,005 |
37 | // Internal functions /Adds a new transaction to the transaction mapping, if transaction does not exist yet.destination Transaction target address.value Transaction ether value.data Transaction data payload. return Returns transaction ID. | function addTransaction(address destination, uint value, bytes memory data)
internal
notNull(destination)
returns (uint transactionId)
| function addTransaction(address destination, uint value, bytes memory data)
internal
notNull(destination)
returns (uint transactionId)
| 48,311 |
3 | // This event is emitted when a new access controller is set/oldAccessController The old access controller address/newAccessController The new access controller address | event AccessControllerSet(address oldAccessController, address newAccessController);
| event AccessControllerSet(address oldAccessController, address newAccessController);
| 19,151 |
98 | // ZeppelinOS Initializer Function_totalSupply The total supply of the tokens_rewardsPoolAddress address of Rewards Pool contract_rewardsPoolPercentage percentage to be taken from payments and sent to rewards pool_owner contract owner/ | function initialize(
uint256 _totalSupply,
address _rewardsPoolAddress,
uint256 _rewardsPoolPercentage,
address _owner
) public initializer {
| function initialize(
uint256 _totalSupply,
address _rewardsPoolAddress,
uint256 _rewardsPoolPercentage,
address _owner
) public initializer {
| 27,910 |
19 | // We transfer the ETHs from contract to user TODO: change it for sendValue, function from address payable (OpenZeppelin address class) TODO: check posible reentrancy | payable(msg.sender).transfer(ethsBought);
| payable(msg.sender).transfer(ethsBought);
| 4,478 |
16 | // A bank locks ERC721 tokens. It doesn't contain any exchange logics that helps upgrade the exchange contract./ Users have complete control over their assets. Only user trusted contracts are able to access the assets. | contract ERC721Bank is IBank, Authorizable, ReentrancyGuard {
using LibBytes for bytes;
mapping(address => mapping(address => uint256[])) public deposits;
event Deposit(address token, address user, uint256 tokenId, uint256[] balance);
event Withdraw(address token, address user, uint256 tokenId, uint256[] balance);
event TransferFallback(address token);
/// Checks whether the user has enough deposit.
/// @param token Token address.
/// @param user User address.
/// @param data Additional token data (e.g. tokenId for ERC721).
/// @return Whether the user has enough deposit.
function hasDeposit(address token, address user, uint256, bytes memory data) public view returns (bool) {
for (uint256 i = 0; i < deposits[token][user].length; i++) {
if (data.readUint256(0) == deposits[token][user][i]) {
return true;
}
}
return false;
}
/// Checks token balance available to use (including user deposit amount + user approved allowance amount).
/// @param token Token address.
/// @param user User address.
/// @param data Additional token data (e.g. tokenId for ERC721).
/// @return Token amount available.
function getAvailable(address token, address user, bytes calldata data) external view returns (uint256) {
uint256 tokenId = data.readUint256(0);
if ((IERC721(token).getApproved(tokenId) == address(this) && IERC721(token).ownerOf(tokenId) == user) ||
this.hasDeposit(token, user, 1, data)) {
return 1;
}
return 0;
}
/// Gets balance of user's deposit.
/// @param token Token address.
/// @param user User address.
/// @return Token deposit amount.
function balanceOf(address token, address user) public view returns (uint256) {
return deposits[token][user].length;
}
/// Gets an array of ERC721 tokenIds owned by user in deposit.
/// @param token Token address.
/// @param user User address.
function getTokenIds(address token, address user) external view returns (uint256[] memory) {
return deposits[token][user];
}
/// Deposits token from user wallet to bank.
/// @param token Token address.
/// @param user User address (allows third-party give tokens to any users).
/// @param data Additional token data (e.g. tokenId for ERC721).
function deposit(address token, address user, uint256, bytes calldata data) external nonReentrant payable {
uint256 tokenId = data.readUint256(0);
IERC721(token).transferFrom(msg.sender, address(this), tokenId);
deposits[token][user].push(tokenId);
emit Deposit(token, user, tokenId, deposits[token][user]);
}
/// Withdraws token from bank to user wallet.
/// @param token Token address.
/// @param data Additional token data (e.g. tokenId for ERC721).
function withdraw(address token, uint256, bytes calldata data) external nonReentrant {
uint256 tokenId = data.readUint256(0);
require(hasDeposit(token, msg.sender, tokenId, data), "INSUFFICIENT_DEPOSIT");
removeToken(token, msg.sender, tokenId);
transferFallback(token, msg.sender, tokenId);
emit Withdraw(token, msg.sender, tokenId, deposits[token][msg.sender]);
}
/// Transfers token from one address to another address.
/// Only caller who are double-approved by both bank owner and token owner can invoke this function.
/// @param token Token address.
/// @param from The current token owner address.
/// @param to The new token owner address.
/// @param amount Token amount.
/// @param data Additional token data (e.g. tokenId for ERC721).
/// @param fromDeposit True if use fund from bank deposit. False if use fund from user wallet.
/// @param toDeposit True if deposit fund to bank deposit. False if send fund to user wallet.
function transferFrom(
address token,
address from,
address to,
uint256 amount,
bytes calldata data,
bool fromDeposit,
bool toDeposit
)
external
onlyAuthorized
onlyUserApproved(from)
nonReentrant
{
if (amount == 0 || from == to) {
return;
}
uint256 tokenId = data.readUint256(0);
if (fromDeposit) {
require(hasDeposit(token, from, tokenId, data));
removeToken(token, from, tokenId);
if (toDeposit) {
// Deposit to deposit
deposits[token][to].push(tokenId);
} else {
// Deposit to wallet
transferFallback(token, to, tokenId);
}
} else {
if (toDeposit) {
// Wallet to deposit
IERC721(token).transferFrom(from, address(this), tokenId);
deposits[token][to].push(tokenId);
} else {
// Wallet to wallet
IERC721(token).transferFrom(from, to, tokenId);
}
}
}
/// Some older tokens only implement transfer(...) instead of transferFrom(...) which required by ERC721 standard.
/// First, the function tries to call transferFrom(...) using raw assembly call to avoid EVM reverts.
/// If failed, call transfer(...) as a fallback.
/// @param token Token address.
/// @param to The new token owner address.
/// @param tokenId Token ID.
function transferFallback(address token, address to, uint256 tokenId) internal {
bytes memory callData = abi.encodeWithSelector(
IERC721(token).transferFrom.selector,
address(this),
to,
tokenId
);
bool result;
assembly {
let cdStart := add(callData, 32)
result := call(
gas, // forward all gas
token, // address of token contract
0, // don't send any ETH
cdStart, // pointer to start of input
mload(callData), // length of input
cdStart, // write output over input
0 // output size is 0
)
}
if (!result) {
IERC721(token).transfer(to, tokenId);
emit TransferFallback(token);
}
}
/// Remove token from deposit.
/// @param token Token address.
/// @param user User address.
/// @param tokenId Token ID.
function removeToken(address token, address user, uint256 tokenId) internal {
for (uint256 i = 0; i < deposits[token][user].length; i++) {
if (tokenId == deposits[token][user][i]) {
deposits[token][user][i] = deposits[token][user][deposits[token][user].length - 1];
delete deposits[token][user][deposits[token][user].length - 1];
deposits[token][user].length--;
return;
}
}
}
}
| contract ERC721Bank is IBank, Authorizable, ReentrancyGuard {
using LibBytes for bytes;
mapping(address => mapping(address => uint256[])) public deposits;
event Deposit(address token, address user, uint256 tokenId, uint256[] balance);
event Withdraw(address token, address user, uint256 tokenId, uint256[] balance);
event TransferFallback(address token);
/// Checks whether the user has enough deposit.
/// @param token Token address.
/// @param user User address.
/// @param data Additional token data (e.g. tokenId for ERC721).
/// @return Whether the user has enough deposit.
function hasDeposit(address token, address user, uint256, bytes memory data) public view returns (bool) {
for (uint256 i = 0; i < deposits[token][user].length; i++) {
if (data.readUint256(0) == deposits[token][user][i]) {
return true;
}
}
return false;
}
/// Checks token balance available to use (including user deposit amount + user approved allowance amount).
/// @param token Token address.
/// @param user User address.
/// @param data Additional token data (e.g. tokenId for ERC721).
/// @return Token amount available.
function getAvailable(address token, address user, bytes calldata data) external view returns (uint256) {
uint256 tokenId = data.readUint256(0);
if ((IERC721(token).getApproved(tokenId) == address(this) && IERC721(token).ownerOf(tokenId) == user) ||
this.hasDeposit(token, user, 1, data)) {
return 1;
}
return 0;
}
/// Gets balance of user's deposit.
/// @param token Token address.
/// @param user User address.
/// @return Token deposit amount.
function balanceOf(address token, address user) public view returns (uint256) {
return deposits[token][user].length;
}
/// Gets an array of ERC721 tokenIds owned by user in deposit.
/// @param token Token address.
/// @param user User address.
function getTokenIds(address token, address user) external view returns (uint256[] memory) {
return deposits[token][user];
}
/// Deposits token from user wallet to bank.
/// @param token Token address.
/// @param user User address (allows third-party give tokens to any users).
/// @param data Additional token data (e.g. tokenId for ERC721).
function deposit(address token, address user, uint256, bytes calldata data) external nonReentrant payable {
uint256 tokenId = data.readUint256(0);
IERC721(token).transferFrom(msg.sender, address(this), tokenId);
deposits[token][user].push(tokenId);
emit Deposit(token, user, tokenId, deposits[token][user]);
}
/// Withdraws token from bank to user wallet.
/// @param token Token address.
/// @param data Additional token data (e.g. tokenId for ERC721).
function withdraw(address token, uint256, bytes calldata data) external nonReentrant {
uint256 tokenId = data.readUint256(0);
require(hasDeposit(token, msg.sender, tokenId, data), "INSUFFICIENT_DEPOSIT");
removeToken(token, msg.sender, tokenId);
transferFallback(token, msg.sender, tokenId);
emit Withdraw(token, msg.sender, tokenId, deposits[token][msg.sender]);
}
/// Transfers token from one address to another address.
/// Only caller who are double-approved by both bank owner and token owner can invoke this function.
/// @param token Token address.
/// @param from The current token owner address.
/// @param to The new token owner address.
/// @param amount Token amount.
/// @param data Additional token data (e.g. tokenId for ERC721).
/// @param fromDeposit True if use fund from bank deposit. False if use fund from user wallet.
/// @param toDeposit True if deposit fund to bank deposit. False if send fund to user wallet.
function transferFrom(
address token,
address from,
address to,
uint256 amount,
bytes calldata data,
bool fromDeposit,
bool toDeposit
)
external
onlyAuthorized
onlyUserApproved(from)
nonReentrant
{
if (amount == 0 || from == to) {
return;
}
uint256 tokenId = data.readUint256(0);
if (fromDeposit) {
require(hasDeposit(token, from, tokenId, data));
removeToken(token, from, tokenId);
if (toDeposit) {
// Deposit to deposit
deposits[token][to].push(tokenId);
} else {
// Deposit to wallet
transferFallback(token, to, tokenId);
}
} else {
if (toDeposit) {
// Wallet to deposit
IERC721(token).transferFrom(from, address(this), tokenId);
deposits[token][to].push(tokenId);
} else {
// Wallet to wallet
IERC721(token).transferFrom(from, to, tokenId);
}
}
}
/// Some older tokens only implement transfer(...) instead of transferFrom(...) which required by ERC721 standard.
/// First, the function tries to call transferFrom(...) using raw assembly call to avoid EVM reverts.
/// If failed, call transfer(...) as a fallback.
/// @param token Token address.
/// @param to The new token owner address.
/// @param tokenId Token ID.
function transferFallback(address token, address to, uint256 tokenId) internal {
bytes memory callData = abi.encodeWithSelector(
IERC721(token).transferFrom.selector,
address(this),
to,
tokenId
);
bool result;
assembly {
let cdStart := add(callData, 32)
result := call(
gas, // forward all gas
token, // address of token contract
0, // don't send any ETH
cdStart, // pointer to start of input
mload(callData), // length of input
cdStart, // write output over input
0 // output size is 0
)
}
if (!result) {
IERC721(token).transfer(to, tokenId);
emit TransferFallback(token);
}
}
/// Remove token from deposit.
/// @param token Token address.
/// @param user User address.
/// @param tokenId Token ID.
function removeToken(address token, address user, uint256 tokenId) internal {
for (uint256 i = 0; i < deposits[token][user].length; i++) {
if (tokenId == deposits[token][user][i]) {
deposits[token][user][i] = deposits[token][user][deposits[token][user].length - 1];
delete deposits[token][user][deposits[token][user].length - 1];
deposits[token][user].length--;
return;
}
}
}
}
| 42,224 |
35 | // external functions | function addLiquidity() external onlyOwner() {
require(!_tradingOpen, "Trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _totalSupply);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
| function addLiquidity() external onlyOwner() {
require(!_tradingOpen, "Trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _totalSupply);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
| 11,580 |
3 | // Initializes the template with the version number and default parameters. This is called when templates are upgraded and will revert if the template has already been initialized.To downgrade a template, the original template must be redeployed first. / | function _initializeTemplate(CollectionType collectionType, address implementation, uint256 version) internal {
// Set the template creator to 0 so that it may never be self destructed.
address payable creator = payable(0);
string memory symbol = version.toString();
string memory name = string.concat(getCollectionTypeName(collectionType), " Implementation v", symbol);
// getCollectionTypeName reverts if the collection type is NULL.
if (collectionType == CollectionType.NFTCollection) {
symbol = string.concat("NFTv", symbol);
INFTCollectionInitializer(implementation).initialize(creator, name, symbol);
} else if (collectionType == CollectionType.NFTDropCollection) {
symbol = string.concat("NFTDropV", symbol);
INFTDropCollectionInitializer(implementation).initialize({
_creator: creator,
_name: name,
_symbol: symbol,
_baseURI: "ipfs://QmUtCsULTpfUYWBfcUS1y25rqBZ6E5CfKzZg6j9P3gFScK/",
isRevealed: true,
_maxTokenId: 1,
_approvedMinter: address(0),
_paymentAddress: payable(0)
});
} else {
// if (collectionType == CollectionType.NFTTimedEditionCollection)
symbol = string.concat("NFTTimedEditionV", symbol);
INFTTimedEditionCollectionInitializer(implementation).initialize({
_creator: creator,
_name: name,
_symbol: symbol,
tokenURI_: "ipfs://QmUtCsULTpfUYWBfcUS1y25rqBZ6E5CfKzZg6j9P3gFScK/",
_mintEndTime: block.timestamp + 1,
_approvedMinter: address(0),
_paymentAddress: payable(0)
});
}
}
| function _initializeTemplate(CollectionType collectionType, address implementation, uint256 version) internal {
// Set the template creator to 0 so that it may never be self destructed.
address payable creator = payable(0);
string memory symbol = version.toString();
string memory name = string.concat(getCollectionTypeName(collectionType), " Implementation v", symbol);
// getCollectionTypeName reverts if the collection type is NULL.
if (collectionType == CollectionType.NFTCollection) {
symbol = string.concat("NFTv", symbol);
INFTCollectionInitializer(implementation).initialize(creator, name, symbol);
} else if (collectionType == CollectionType.NFTDropCollection) {
symbol = string.concat("NFTDropV", symbol);
INFTDropCollectionInitializer(implementation).initialize({
_creator: creator,
_name: name,
_symbol: symbol,
_baseURI: "ipfs://QmUtCsULTpfUYWBfcUS1y25rqBZ6E5CfKzZg6j9P3gFScK/",
isRevealed: true,
_maxTokenId: 1,
_approvedMinter: address(0),
_paymentAddress: payable(0)
});
} else {
// if (collectionType == CollectionType.NFTTimedEditionCollection)
symbol = string.concat("NFTTimedEditionV", symbol);
INFTTimedEditionCollectionInitializer(implementation).initialize({
_creator: creator,
_name: name,
_symbol: symbol,
tokenURI_: "ipfs://QmUtCsULTpfUYWBfcUS1y25rqBZ6E5CfKzZg6j9P3gFScK/",
_mintEndTime: block.timestamp + 1,
_approvedMinter: address(0),
_paymentAddress: payable(0)
});
}
}
| 20,081 |
2 | // Validate a trading limit configuration. Reverts if the configuration is malformed. self the Config struct to check. / | function validate(Config memory self) internal pure {
require(self.flags & L1 == 0 || self.flags & L0 != 0, "L1 without L0 not allowed");
require(self.flags & L0 == 0 || self.timestep0 > 0, "timestep0 can't be zero if active");
require(self.flags & L1 == 0 || self.timestep1 > 0, "timestep1 can't be zero if active");
}
| function validate(Config memory self) internal pure {
require(self.flags & L1 == 0 || self.flags & L0 != 0, "L1 without L0 not allowed");
require(self.flags & L0 == 0 || self.timestep0 > 0, "timestep0 can't be zero if active");
require(self.flags & L1 == 0 || self.timestep1 > 0, "timestep1 can't be zero if active");
}
| 26,002 |
172 | // https:eips.ethereum.org/EIPS/eip-3156lender-specification | function flashLoan(IERC3156FlashBorrower _receiver, address _token, uint256 _amount, bytes memory _data) public override nonReentrantWithWhitelist discountCHI returns (bool){
require(loanEnabled == true, "!loanEnabled");
require(_amount > 0, "amount too small!");
require(address(_token) == address(token), "!_token");
uint256 beforeBalance = token.balanceOf(address(this));
require(beforeBalance > _amount, "balance not enough!");
// keep track of Vault balance for sanity check
uint256 _totalBalBefore = balance();
//loanFee
uint256 _fee = _amount.mul(loanFee).div(loanFeeMax);
require(_fee > 0, "fee too small");
//transfer token to _receiver
token.safeTransfer(address(_receiver), _amount);
//execute user's logic
IERC3156FlashBorrower(_receiver).onFlashLoan(address(msg.sender), address(token), _amount, _fee, _data);
// pull repayment from _receiver
uint256 _totalDue = _amount.add(_fee);
token.safeTransferFrom(address(_receiver), address(this), _totalDue);
// ensure we got correct balance after flashloan
uint256 _totalBalAfter = balance();
require(_totalBalAfter == _totalBalBefore.add(_fee), "payback amount incorrect!");
emit FlashLoan(address(msg.sender), address(token), address(_receiver), _amount, _fee);
return true;
}
| function flashLoan(IERC3156FlashBorrower _receiver, address _token, uint256 _amount, bytes memory _data) public override nonReentrantWithWhitelist discountCHI returns (bool){
require(loanEnabled == true, "!loanEnabled");
require(_amount > 0, "amount too small!");
require(address(_token) == address(token), "!_token");
uint256 beforeBalance = token.balanceOf(address(this));
require(beforeBalance > _amount, "balance not enough!");
// keep track of Vault balance for sanity check
uint256 _totalBalBefore = balance();
//loanFee
uint256 _fee = _amount.mul(loanFee).div(loanFeeMax);
require(_fee > 0, "fee too small");
//transfer token to _receiver
token.safeTransfer(address(_receiver), _amount);
//execute user's logic
IERC3156FlashBorrower(_receiver).onFlashLoan(address(msg.sender), address(token), _amount, _fee, _data);
// pull repayment from _receiver
uint256 _totalDue = _amount.add(_fee);
token.safeTransferFrom(address(_receiver), address(this), _totalDue);
// ensure we got correct balance after flashloan
uint256 _totalBalAfter = balance();
require(_totalBalAfter == _totalBalBefore.add(_fee), "payback amount incorrect!");
emit FlashLoan(address(msg.sender), address(token), address(_receiver), _amount, _fee);
return true;
}
| 5,769 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.