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
|
---|---|---|---|---|
49 | // Gets the total amount of tokens stored by the contractreturn uint256 representing the total amount of tokens / | function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
| function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
| 17,927 |
10 | // Repay Flash loan | manager.repayAaveLoan(loanAddress);
| manager.repayAaveLoan(loanAddress);
| 6,991 |
162 | // Setter for the maths utils address _mathsUtils the address of the new math utils / | function setMathsUtils(address _mathsUtils) external;
| function setMathsUtils(address _mathsUtils) external;
| 23,700 |
83 | // Number of consecutive blocks where there must be no new interest before bonus ends. | uint constant public BONUS_LATCH = 2;
| uint constant public BONUS_LATCH = 2;
| 7,855 |
24 | // Liquidate a position. Liquidate a position. borrower Borrower's Address. tokenToPay The address of the token to pay for liquidation.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) cTokenPay Corresponding cToken address. tokenInReturn The address of the token to return for liquidation. cTokenColl Corresponding cToken address. amt The token amount to pay for liquidation. getId ID to retrieve amt. setId ID stores the amount of paid for liquidation./ | function liquidateRaw(
address borrower,
address tokenToPay,
address cTokenPay,
address tokenInReturn,
address cTokenColl,
uint256 amt,
uint256 getId,
uint256 setId
| function liquidateRaw(
address borrower,
address tokenToPay,
address cTokenPay,
address tokenInReturn,
address cTokenColl,
uint256 amt,
uint256 getId,
uint256 setId
| 18,742 |
2 | // ================================================== constractor ================================================== | constructor() {
_grantRole(ADMIN, msg.sender);
}
| constructor() {
_grantRole(ADMIN, msg.sender);
}
| 663 |
22 | // of those NFTs is `${baseURIForTokens}/${tokenId}`._data Additional bytes data to be used at the discretion of the consumer of the contract. return batchIdA unique integer identifier for the batch of NFTs lazy minted together. / | function lazyMint(
uint256 _amount,
string calldata _baseURIForTokens,
bytes calldata _data
) public virtual override returns (uint256 batchId) {
if (!_canLazyMint()) {
revert AuthError();
}
| function lazyMint(
uint256 _amount,
string calldata _baseURIForTokens,
bytes calldata _data
) public virtual override returns (uint256 batchId) {
if (!_canLazyMint()) {
revert AuthError();
}
| 2,908 |
2 | // Mapping fot pictures |
mapping(uint256 => Picture) public pictures;
|
mapping(uint256 => Picture) public pictures;
| 25,635 |
122 | // Function that puts the funds to work.It gets called whenever someone deposits in the strategy's vault contract.It deposits soak in the MasterChef to earn rewards in soak. / | function deposit() public whenNotPaused {
uint256 soakBal = IERC20(soak).balanceOf(address(this));
if (soakBal > 0) {
IMasterChef(masterchef).enterStaking(soakBal);
}
}
| function deposit() public whenNotPaused {
uint256 soakBal = IERC20(soak).balanceOf(address(this));
if (soakBal > 0) {
IMasterChef(masterchef).enterStaking(soakBal);
}
}
| 13,632 |
5 | // Returns the length of a null-terminated bytes32 string. self The value to find the length of.return The length of the string, from 0 to 32. / | function len(bytes32 self) internal returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
| function len(bytes32 self) internal returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
| 34,964 |
57 | // AutoLP tax, keep these variables same, DO NOT CHANGE | _autoLPFee = _autoLpTaxBPS / 2;
_liquidityFee = _autoLpTaxBPS / 2;
_totalTax = _taxFee + _developmentFee + _autoLPFee + _liquidityFee;
require(_totalTax <= 1500, "total tax cannot exceed 15%");
require((_developmentFee + _autoLPFee) >= 100, "ERR: development + autoLP fee should exceed 1%");
_updatePairsFee((_developmentFee + _autoLPFee));
| _autoLPFee = _autoLpTaxBPS / 2;
_liquidityFee = _autoLpTaxBPS / 2;
_totalTax = _taxFee + _developmentFee + _autoLPFee + _liquidityFee;
require(_totalTax <= 1500, "total tax cannot exceed 15%");
require((_developmentFee + _autoLPFee) >= 100, "ERR: development + autoLP fee should exceed 1%");
_updatePairsFee((_developmentFee + _autoLPFee));
| 22,136 |
23 | // Transfer premium payment to writer | Opts[ID].writer.transfer(Opts[ID].premium);
Opts[ID].buyer = msg.sender;
| Opts[ID].writer.transfer(Opts[ID].premium);
Opts[ID].buyer = msg.sender;
| 12,334 |
14 | // Event which is triggered to log all transfers to this contract's event log | event Transfer(
address indexed _from,
address indexed _to,
uint _value
);
| event Transfer(
address indexed _from,
address indexed _to,
uint _value
);
| 9,088 |
5 | // Lets a borrower request for a loan. Returned value is type uint256. _lendingToken The address of the token being requested. _poolId The Id of the pool. _principal The principal amount being requested. _duration The duration of the loan. _expirationDuration The time in which the loan has to be accepted before it expires. _APR The annual interest percentage in bps. _receiver The receiver of the funds.return loanId_ Id of the loan. / | function loanRequest(
address _lendingToken,
uint256 _poolId,
uint256 _principal,
uint32 _duration,
uint32 _expirationDuration,
uint16 _APR,
address _receiver
| function loanRequest(
address _lendingToken,
uint256 _poolId,
uint256 _principal,
uint32 _duration,
uint32 _expirationDuration,
uint16 _APR,
address _receiver
| 23,110 |
21 | // Function allow ADMIN set max tokens per one use / | function setMaxTokensInOneUsing(uint8 _maxTokenInOneUsing) external onlyRole(DEFAULT_ADMIN_ROLE) {
MAX_TOKENS_IN_USING = _maxTokenInOneUsing;
emit SetMaxTokensInOneUsing(_maxTokenInOneUsing);
}
| function setMaxTokensInOneUsing(uint8 _maxTokenInOneUsing) external onlyRole(DEFAULT_ADMIN_ROLE) {
MAX_TOKENS_IN_USING = _maxTokenInOneUsing;
emit SetMaxTokensInOneUsing(_maxTokenInOneUsing);
}
| 7,340 |
77 | // src/UniswapConsecutiveSlotsPriceFeedMedianizer.sol/ pragma solidity 0.6.7; // import "geb-treasury-reimbursement/math/GebMath.sol"; // import './uni/interfaces/IUniswapV2Factory.sol'; // import './uni/interfaces/IUniswapV2Pair.sol'; // import './uni/libs/UniswapV2Library.sol'; // import './uni/libs/UniswapV2OracleLibrary.sol'; / | abstract contract ConverterFeedLike_1 {
function getResultWithValidity() virtual external view returns (uint256,bool);
function updateResult(address) virtual external;
}
abstract contract IncreasingRewardRelayerLike_1 {
function reimburseCaller(address) virtual external;
}
contract UniswapConsecutiveSlotsPriceFeedMedianizer is GebMath, UniswapV2Library, UniswapV2OracleLibrary {
// --- Auth ---
mapping (address => uint) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
| abstract contract ConverterFeedLike_1 {
function getResultWithValidity() virtual external view returns (uint256,bool);
function updateResult(address) virtual external;
}
abstract contract IncreasingRewardRelayerLike_1 {
function reimburseCaller(address) virtual external;
}
contract UniswapConsecutiveSlotsPriceFeedMedianizer is GebMath, UniswapV2Library, UniswapV2OracleLibrary {
// --- Auth ---
mapping (address => uint) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
| 73,545 |
85 | // Swap exact number of NOCLAIM tokens for DAI on Balancer | _approve(noclaimToken, address(data.bpool), mintAmount);
(uint256 daiReceived, ) = data.bpool.swapExactAmountIn(
address(noclaimToken),
mintAmount,
address(dai),
0,
type(uint256).max
);
require(daiReceived > 0, "received 0 DAI from swap");
| _approve(noclaimToken, address(data.bpool), mintAmount);
(uint256 daiReceived, ) = data.bpool.swapExactAmountIn(
address(noclaimToken),
mintAmount,
address(dai),
0,
type(uint256).max
);
require(daiReceived > 0, "received 0 DAI from swap");
| 42,733 |
2 | // Initializes governing token./dao_ address of cloned DAO./factory_ address of factory./supply_ total supply of tokens. | function initializeCustom(address dao_, address factory_, uint256 supply_) external;
| function initializeCustom(address dao_, address factory_, uint256 supply_) external;
| 27,356 |
73 | // set signing address after deployment | function setSigner(address _signer) public onlyOwner {
require(_signer != address(0));
signer = _signer;
}
| function setSigner(address _signer) public onlyOwner {
require(_signer != address(0));
signer = _signer;
}
| 14,412 |
47 | // See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is notrequired by the EIP. See the note at the beginning of {ERC20}. NOTE: Does not update the allowance if the current allowanceis the maximum `uint256`. Requirements: - `from` and `to` cannot be the zero address.- `from` must have a balance of at least `value`.- the caller must have allowance for ``from``'s tokens of at least`value`. / | function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
| function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
| 33,581 |
13 | // return {UoA/target} The price of a target unit in UoA | function pricePerTarget() public view virtual returns (uint192) {
return FIX_ONE;
}
| function pricePerTarget() public view virtual returns (uint192) {
return FIX_ONE;
}
| 27,595 |
94 | // Mint tokens for crowdsale participants investorsAddress List of Purchasers addresses amountOfTokens List of token amounts for investor / | function mintTokensForCrowdsaleParticipants(address[] investorsAddress, uint256[] amountOfTokens)
external
onlyOwner
| function mintTokensForCrowdsaleParticipants(address[] investorsAddress, uint256[] amountOfTokens)
external
onlyOwner
| 33,322 |
24 | // set true | request.recipient.transfer(request.value);
request.complete = true;
| request.recipient.transfer(request.value);
request.complete = true;
| 27,216 |
22 | // Removes a key-value pair from a map. O(1). Returns true if the key was removed from the map, that is if it was present. / | function _remove(CardMap storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
CardEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._tokenId] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
| function _remove(CardMap storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
CardEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._tokenId] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
| 15,572 |
16 | // Constructor _nom The numerator to calculate the global `reserveRatioDailyExpansion` from _denom The denominator to calculate the global `reserveRatioDailyExpansion` from / | function initialize(
INameService _ns,
uint256 _nom,
uint256 _denom
| function initialize(
INameService _ns,
uint256 _nom,
uint256 _denom
| 47,745 |
137 | // Based on https:github.com/madler/zlib/blob/master/contrib/puff | library InflateLib {
// Maximum bits in a code
uint256 constant MAXBITS = 15;
// Maximum number of literal/length codes
uint256 constant MAXLCODES = 286;
// Maximum number of distance codes
uint256 constant MAXDCODES = 30;
// Maximum codes lengths to read
uint256 constant MAXCODES = (MAXLCODES + MAXDCODES);
// Number of fixed literal/length codes
uint256 constant FIXLCODES = 288;
// Error codes
enum ErrorCode {
ERR_NONE, // 0 successful inflate
ERR_NOT_TERMINATED, // 1 available inflate data did not terminate
ERR_OUTPUT_EXHAUSTED, // 2 output space exhausted before completing inflate
ERR_INVALID_BLOCK_TYPE, // 3 invalid block type (type == 3)
ERR_STORED_LENGTH_NO_MATCH, // 4 stored block length did not match one's complement
ERR_TOO_MANY_LENGTH_OR_DISTANCE_CODES, // 5 dynamic block code description: too many length or distance codes
ERR_CODE_LENGTHS_CODES_INCOMPLETE, // 6 dynamic block code description: code lengths codes incomplete
ERR_REPEAT_NO_FIRST_LENGTH, // 7 dynamic block code description: repeat lengths with no first length
ERR_REPEAT_MORE, // 8 dynamic block code description: repeat more than specified lengths
ERR_INVALID_LITERAL_LENGTH_CODE_LENGTHS, // 9 dynamic block code description: invalid literal/length code lengths
ERR_INVALID_DISTANCE_CODE_LENGTHS, // 10 dynamic block code description: invalid distance code lengths
ERR_MISSING_END_OF_BLOCK, // 11 dynamic block code description: missing end-of-block code
ERR_INVALID_LENGTH_OR_DISTANCE_CODE, // 12 invalid literal/length or distance code in fixed or dynamic block
ERR_DISTANCE_TOO_FAR, // 13 distance is too far back in fixed or dynamic block
ERR_CONSTRUCT // 14 internal: error in construct()
}
// Input and output state
struct State {
//////////////////
// Output state //
//////////////////
// Output buffer
bytes output;
// Bytes written to out so far
uint256 outcnt;
/////////////////
// Input state //
/////////////////
// Input buffer
bytes input;
// Bytes read so far
uint256 incnt;
////////////////
// Temp state //
////////////////
// Bit buffer
uint256 bitbuf;
// Number of bits in bit buffer
uint256 bitcnt;
//////////////////////////
// Static Huffman codes //
//////////////////////////
Huffman lencode;
Huffman distcode;
}
// Huffman code decoding tables
struct Huffman {
uint256[] counts;
uint256[] symbols;
}
function bits(State memory s, uint256 need)
private
pure
returns (ErrorCode, uint256)
{
// Bit accumulator (can use up to 20 bits)
uint256 val;
// Load at least need bits into val
val = s.bitbuf;
while (s.bitcnt < need) {
if (s.incnt == s.input.length) {
// Out of input
return (ErrorCode.ERR_NOT_TERMINATED, 0);
}
// Load eight bits
val |= uint256(uint8(s.input[s.incnt++])) << s.bitcnt;
s.bitcnt += 8;
}
// Drop need bits and update buffer, always zero to seven bits left
s.bitbuf = val >> need;
s.bitcnt -= need;
// Return need bits, zeroing the bits above that
uint256 ret = (val & ((1 << need) - 1));
return (ErrorCode.ERR_NONE, ret);
}
function _stored(State memory s) private pure returns (ErrorCode) {
// Length of stored block
uint256 len;
// Discard leftover bits from current byte (assumes s.bitcnt < 8)
s.bitbuf = 0;
s.bitcnt = 0;
// Get length and check against its one's complement
if (s.incnt + 4 > s.input.length) {
// Not enough input
return ErrorCode.ERR_NOT_TERMINATED;
}
len = uint256(uint8(s.input[s.incnt++]));
len |= uint256(uint8(s.input[s.incnt++])) << 8;
if (
uint8(s.input[s.incnt++]) != (~len & 0xFF) ||
uint8(s.input[s.incnt++]) != ((~len >> 8) & 0xFF)
) {
// Didn't match complement!
return ErrorCode.ERR_STORED_LENGTH_NO_MATCH;
}
// Copy len bytes from in to out
if (s.incnt + len > s.input.length) {
// Not enough input
return ErrorCode.ERR_NOT_TERMINATED;
}
if (s.outcnt + len > s.output.length) {
// Not enough output space
return ErrorCode.ERR_OUTPUT_EXHAUSTED;
}
while (len != 0) {
// Note: Solidity reverts on underflow, so we decrement here
len -= 1;
s.output[s.outcnt++] = s.input[s.incnt++];
}
// Done with a valid stored block
return ErrorCode.ERR_NONE;
}
function _decode(State memory s, Huffman memory h)
private
pure
returns (ErrorCode, uint256)
{
// Current number of bits in code
uint256 len;
// Len bits being decoded
uint256 code = 0;
// First code of length len
uint256 first = 0;
// Number of codes of length len
uint256 count;
// Index of first code of length len in symbol table
uint256 index = 0;
// Error code
ErrorCode err;
for (len = 1; len <= MAXBITS; len++) {
// Get next bit
uint256 tempCode;
(err, tempCode) = bits(s, 1);
if (err != ErrorCode.ERR_NONE) {
return (err, 0);
}
code |= tempCode;
count = h.counts[len];
// If length len, return symbol
if (code < first + count) {
return (ErrorCode.ERR_NONE, h.symbols[index + (code - first)]);
}
// Else update for next length
index += count;
first += count;
first <<= 1;
code <<= 1;
}
// Ran out of codes
return (ErrorCode.ERR_INVALID_LENGTH_OR_DISTANCE_CODE, 0);
}
function _construct(
Huffman memory h,
uint256[] memory lengths,
uint256 n,
uint256 start
) private pure returns (ErrorCode) {
// Current symbol when stepping through lengths[]
uint256 symbol;
// Current length when stepping through h.counts[]
uint256 len;
// Number of possible codes left of current length
uint256 left;
// Offsets in symbol table for each length
uint256[MAXBITS + 1] memory offs;
// Count number of codes of each length
for (len = 0; len <= MAXBITS; len++) {
h.counts[len] = 0;
}
for (symbol = 0; symbol < n; symbol++) {
// Assumes lengths are within bounds
h.counts[lengths[start + symbol]]++;
}
// No codes!
if (h.counts[0] == n) {
// Complete, but decode() will fail
return (ErrorCode.ERR_NONE);
}
// Check for an over-subscribed or incomplete set of lengths
// One possible code of zero length
left = 1;
for (len = 1; len <= MAXBITS; len++) {
// One more bit, double codes left
left <<= 1;
if (left < h.counts[len]) {
// Over-subscribed--return error
return ErrorCode.ERR_CONSTRUCT;
}
// Deduct count from possible codes
left -= h.counts[len];
}
// Generate offsets into symbol table for each length for sorting
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + h.counts[len];
}
// Put symbols in table sorted by length, by symbol order within each length
for (symbol = 0; symbol < n; symbol++) {
if (lengths[start + symbol] != 0) {
h.symbols[offs[lengths[start + symbol]]++] = symbol;
}
}
// Left > 0 means incomplete
return left > 0 ? ErrorCode.ERR_CONSTRUCT : ErrorCode.ERR_NONE;
}
function _codes(
State memory s,
Huffman memory lencode,
Huffman memory distcode
) private pure returns (ErrorCode) {
// Decoded symbol
uint256 symbol;
// Length for copy
uint256 len;
// Distance for copy
uint256 dist;
// TODO Solidity doesn't support constant arrays, but these are fixed at compile-time
// Size base for length codes 257..285
uint16[29] memory lens =
[
3,
4,
5,
6,
7,
8,
9,
10,
11,
13,
15,
17,
19,
23,
27,
31,
35,
43,
51,
59,
67,
83,
99,
115,
131,
163,
195,
227,
258
];
// Extra bits for length codes 257..285
uint8[29] memory lext =
[
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
2,
2,
2,
2,
3,
3,
3,
3,
4,
4,
4,
4,
5,
5,
5,
5,
0
];
// Offset base for distance codes 0..29
uint16[30] memory dists =
[
1,
2,
3,
4,
5,
7,
9,
13,
17,
25,
33,
49,
65,
97,
129,
193,
257,
385,
513,
769,
1025,
1537,
2049,
3073,
4097,
6145,
8193,
12289,
16385,
24577
];
// Extra bits for distance codes 0..29
uint8[30] memory dext =
[
0,
0,
0,
0,
1,
1,
2,
2,
3,
3,
4,
4,
5,
5,
6,
6,
7,
7,
8,
8,
9,
9,
10,
10,
11,
11,
12,
12,
13,
13
];
// Error code
ErrorCode err;
// Decode literals and length/distance pairs
while (symbol != 256) {
(err, symbol) = _decode(s, lencode);
if (err != ErrorCode.ERR_NONE) {
// Invalid symbol
return err;
}
if (symbol < 256) {
// Literal: symbol is the byte
// Write out the literal
if (s.outcnt == s.output.length) {
return ErrorCode.ERR_OUTPUT_EXHAUSTED;
}
s.output[s.outcnt] = bytes1(uint8(symbol));
s.outcnt++;
} else if (symbol > 256) {
uint256 tempBits;
// Length
// Get and compute length
symbol -= 257;
if (symbol >= 29) {
// Invalid fixed code
return ErrorCode.ERR_INVALID_LENGTH_OR_DISTANCE_CODE;
}
(err, tempBits) = bits(s, lext[symbol]);
if (err != ErrorCode.ERR_NONE) {
return err;
}
len = lens[symbol] + tempBits;
// Get and check distance
(err, symbol) = _decode(s, distcode);
if (err != ErrorCode.ERR_NONE) {
// Invalid symbol
return err;
}
(err, tempBits) = bits(s, dext[symbol]);
if (err != ErrorCode.ERR_NONE) {
return err;
}
dist = dists[symbol] + tempBits;
if (dist > s.outcnt) {
// Distance too far back
return ErrorCode.ERR_DISTANCE_TOO_FAR;
}
// Copy length bytes from distance bytes back
if (s.outcnt + len > s.output.length) {
return ErrorCode.ERR_OUTPUT_EXHAUSTED;
}
while (len != 0) {
// Note: Solidity reverts on underflow, so we decrement here
len -= 1;
s.output[s.outcnt] = s.output[s.outcnt - dist];
s.outcnt++;
}
} else {
s.outcnt += len;
}
}
// Done with a valid fixed or dynamic block
return ErrorCode.ERR_NONE;
}
function _build_fixed(State memory s) private pure returns (ErrorCode) {
// Build fixed Huffman tables
// TODO this is all a compile-time constant
uint256 symbol;
uint256[] memory lengths = new uint256[](FIXLCODES);
// Literal/length table
for (symbol = 0; symbol < 144; symbol++) {
lengths[symbol] = 8;
}
for (; symbol < 256; symbol++) {
lengths[symbol] = 9;
}
for (; symbol < 280; symbol++) {
lengths[symbol] = 7;
}
for (; symbol < FIXLCODES; symbol++) {
lengths[symbol] = 8;
}
_construct(s.lencode, lengths, FIXLCODES, 0);
// Distance table
for (symbol = 0; symbol < MAXDCODES; symbol++) {
lengths[symbol] = 5;
}
_construct(s.distcode, lengths, MAXDCODES, 0);
return ErrorCode.ERR_NONE;
}
function _fixed(State memory s) private pure returns (ErrorCode) {
// Decode data until end-of-block code
return _codes(s, s.lencode, s.distcode);
}
function _build_dynamic_lengths(State memory s)
private
pure
returns (ErrorCode, uint256[] memory)
{
uint256 ncode;
// Index of lengths[]
uint256 index;
// Descriptor code lengths
uint256[] memory lengths = new uint256[](MAXCODES);
// Error code
ErrorCode err;
// Permutation of code length codes
uint8[19] memory order =
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
(err, ncode) = bits(s, 4);
if (err != ErrorCode.ERR_NONE) {
return (err, lengths);
}
ncode += 4;
// Read code length code lengths (really), missing lengths are zero
for (index = 0; index < ncode; index++) {
(err, lengths[order[index]]) = bits(s, 3);
if (err != ErrorCode.ERR_NONE) {
return (err, lengths);
}
}
for (; index < 19; index++) {
lengths[order[index]] = 0;
}
return (ErrorCode.ERR_NONE, lengths);
}
function _build_dynamic(State memory s)
private
pure
returns (
ErrorCode,
Huffman memory,
Huffman memory
)
{
// Number of lengths in descriptor
uint256 nlen;
uint256 ndist;
// Index of lengths[]
uint256 index;
// Error code
ErrorCode err;
// Descriptor code lengths
uint256[] memory lengths = new uint256[](MAXCODES);
// Length and distance codes
Huffman memory lencode =
Huffman(new uint256[](MAXBITS + 1), new uint256[](MAXLCODES));
Huffman memory distcode =
Huffman(new uint256[](MAXBITS + 1), new uint256[](MAXDCODES));
uint256 tempBits;
// Get number of lengths in each table, check lengths
(err, nlen) = bits(s, 5);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
nlen += 257;
(err, ndist) = bits(s, 5);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
ndist += 1;
if (nlen > MAXLCODES || ndist > MAXDCODES) {
// Bad counts
return (
ErrorCode.ERR_TOO_MANY_LENGTH_OR_DISTANCE_CODES,
lencode,
distcode
);
}
(err, lengths) = _build_dynamic_lengths(s);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
// Build huffman table for code lengths codes (use lencode temporarily)
err = _construct(lencode, lengths, 19, 0);
if (err != ErrorCode.ERR_NONE) {
// Require complete code set here
return (
ErrorCode.ERR_CODE_LENGTHS_CODES_INCOMPLETE,
lencode,
distcode
);
}
// Read length/literal and distance code length tables
index = 0;
while (index < nlen + ndist) {
// Decoded value
uint256 symbol;
// Last length to repeat
uint256 len;
(err, symbol) = _decode(s, lencode);
if (err != ErrorCode.ERR_NONE) {
// Invalid symbol
return (err, lencode, distcode);
}
if (symbol < 16) {
// Length in 0..15
lengths[index++] = symbol;
} else {
// Repeat instruction
// Assume repeating zeros
len = 0;
if (symbol == 16) {
// Repeat last length 3..6 times
if (index == 0) {
// No last length!
return (
ErrorCode.ERR_REPEAT_NO_FIRST_LENGTH,
lencode,
distcode
);
}
// Last length
len = lengths[index - 1];
(err, tempBits) = bits(s, 2);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
symbol = 3 + tempBits;
} else if (symbol == 17) {
// Repeat zero 3..10 times
(err, tempBits) = bits(s, 3);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
symbol = 3 + tempBits;
} else {
// == 18, repeat zero 11..138 times
(err, tempBits) = bits(s, 7);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
symbol = 11 + tempBits;
}
if (index + symbol > nlen + ndist) {
// Too many lengths!
return (ErrorCode.ERR_REPEAT_MORE, lencode, distcode);
}
while (symbol != 0) {
// Note: Solidity reverts on underflow, so we decrement here
symbol -= 1;
// Repeat last or zero symbol times
lengths[index++] = len;
}
}
}
// Check for end-of-block code -- there better be one!
if (lengths[256] == 0) {
return (ErrorCode.ERR_MISSING_END_OF_BLOCK, lencode, distcode);
}
// Build huffman table for literal/length codes
err = _construct(lencode, lengths, nlen, 0);
if (
err != ErrorCode.ERR_NONE &&
(err == ErrorCode.ERR_NOT_TERMINATED ||
err == ErrorCode.ERR_OUTPUT_EXHAUSTED ||
nlen != lencode.counts[0] + lencode.counts[1])
) {
// Incomplete code ok only for single length 1 code
return (
ErrorCode.ERR_INVALID_LITERAL_LENGTH_CODE_LENGTHS,
lencode,
distcode
);
}
// Build huffman table for distance codes
err = _construct(distcode, lengths, ndist, nlen);
if (
err != ErrorCode.ERR_NONE &&
(err == ErrorCode.ERR_NOT_TERMINATED ||
err == ErrorCode.ERR_OUTPUT_EXHAUSTED ||
ndist != distcode.counts[0] + distcode.counts[1])
) {
// Incomplete code ok only for single length 1 code
return (
ErrorCode.ERR_INVALID_DISTANCE_CODE_LENGTHS,
lencode,
distcode
);
}
return (ErrorCode.ERR_NONE, lencode, distcode);
}
function _dynamic(State memory s) private pure returns (ErrorCode) {
// Length and distance codes
Huffman memory lencode;
Huffman memory distcode;
// Error code
ErrorCode err;
(err, lencode, distcode) = _build_dynamic(s);
if (err != ErrorCode.ERR_NONE) {
return err;
}
// Decode data until end-of-block code
return _codes(s, lencode, distcode);
}
function puff(bytes calldata source, uint256 destlen)
internal
pure
returns (ErrorCode, bytes memory)
{
// Input/output state
State memory s =
State(
new bytes(destlen),
0,
source,
0,
0,
0,
Huffman(new uint256[](MAXBITS + 1), new uint256[](FIXLCODES)),
Huffman(new uint256[](MAXBITS + 1), new uint256[](MAXDCODES))
);
// Temp: last bit
uint256 last;
// Temp: block type bit
uint256 t;
// Error code
ErrorCode err;
// Build fixed Huffman tables
err = _build_fixed(s);
if (err != ErrorCode.ERR_NONE) {
return (err, s.output);
}
// Process blocks until last block or error
while (last == 0) {
// One if last block
(err, last) = bits(s, 1);
if (err != ErrorCode.ERR_NONE) {
return (err, s.output);
}
// Block type 0..3
(err, t) = bits(s, 2);
if (err != ErrorCode.ERR_NONE) {
return (err, s.output);
}
err = (
t == 0
? _stored(s)
: (
t == 1
? _fixed(s)
: (
t == 2
? _dynamic(s)
: ErrorCode.ERR_INVALID_BLOCK_TYPE
)
)
);
// type == 3, invalid
if (err != ErrorCode.ERR_NONE) {
// Return with error
break;
}
}
return (err, s.output);
}
}
| library InflateLib {
// Maximum bits in a code
uint256 constant MAXBITS = 15;
// Maximum number of literal/length codes
uint256 constant MAXLCODES = 286;
// Maximum number of distance codes
uint256 constant MAXDCODES = 30;
// Maximum codes lengths to read
uint256 constant MAXCODES = (MAXLCODES + MAXDCODES);
// Number of fixed literal/length codes
uint256 constant FIXLCODES = 288;
// Error codes
enum ErrorCode {
ERR_NONE, // 0 successful inflate
ERR_NOT_TERMINATED, // 1 available inflate data did not terminate
ERR_OUTPUT_EXHAUSTED, // 2 output space exhausted before completing inflate
ERR_INVALID_BLOCK_TYPE, // 3 invalid block type (type == 3)
ERR_STORED_LENGTH_NO_MATCH, // 4 stored block length did not match one's complement
ERR_TOO_MANY_LENGTH_OR_DISTANCE_CODES, // 5 dynamic block code description: too many length or distance codes
ERR_CODE_LENGTHS_CODES_INCOMPLETE, // 6 dynamic block code description: code lengths codes incomplete
ERR_REPEAT_NO_FIRST_LENGTH, // 7 dynamic block code description: repeat lengths with no first length
ERR_REPEAT_MORE, // 8 dynamic block code description: repeat more than specified lengths
ERR_INVALID_LITERAL_LENGTH_CODE_LENGTHS, // 9 dynamic block code description: invalid literal/length code lengths
ERR_INVALID_DISTANCE_CODE_LENGTHS, // 10 dynamic block code description: invalid distance code lengths
ERR_MISSING_END_OF_BLOCK, // 11 dynamic block code description: missing end-of-block code
ERR_INVALID_LENGTH_OR_DISTANCE_CODE, // 12 invalid literal/length or distance code in fixed or dynamic block
ERR_DISTANCE_TOO_FAR, // 13 distance is too far back in fixed or dynamic block
ERR_CONSTRUCT // 14 internal: error in construct()
}
// Input and output state
struct State {
//////////////////
// Output state //
//////////////////
// Output buffer
bytes output;
// Bytes written to out so far
uint256 outcnt;
/////////////////
// Input state //
/////////////////
// Input buffer
bytes input;
// Bytes read so far
uint256 incnt;
////////////////
// Temp state //
////////////////
// Bit buffer
uint256 bitbuf;
// Number of bits in bit buffer
uint256 bitcnt;
//////////////////////////
// Static Huffman codes //
//////////////////////////
Huffman lencode;
Huffman distcode;
}
// Huffman code decoding tables
struct Huffman {
uint256[] counts;
uint256[] symbols;
}
function bits(State memory s, uint256 need)
private
pure
returns (ErrorCode, uint256)
{
// Bit accumulator (can use up to 20 bits)
uint256 val;
// Load at least need bits into val
val = s.bitbuf;
while (s.bitcnt < need) {
if (s.incnt == s.input.length) {
// Out of input
return (ErrorCode.ERR_NOT_TERMINATED, 0);
}
// Load eight bits
val |= uint256(uint8(s.input[s.incnt++])) << s.bitcnt;
s.bitcnt += 8;
}
// Drop need bits and update buffer, always zero to seven bits left
s.bitbuf = val >> need;
s.bitcnt -= need;
// Return need bits, zeroing the bits above that
uint256 ret = (val & ((1 << need) - 1));
return (ErrorCode.ERR_NONE, ret);
}
function _stored(State memory s) private pure returns (ErrorCode) {
// Length of stored block
uint256 len;
// Discard leftover bits from current byte (assumes s.bitcnt < 8)
s.bitbuf = 0;
s.bitcnt = 0;
// Get length and check against its one's complement
if (s.incnt + 4 > s.input.length) {
// Not enough input
return ErrorCode.ERR_NOT_TERMINATED;
}
len = uint256(uint8(s.input[s.incnt++]));
len |= uint256(uint8(s.input[s.incnt++])) << 8;
if (
uint8(s.input[s.incnt++]) != (~len & 0xFF) ||
uint8(s.input[s.incnt++]) != ((~len >> 8) & 0xFF)
) {
// Didn't match complement!
return ErrorCode.ERR_STORED_LENGTH_NO_MATCH;
}
// Copy len bytes from in to out
if (s.incnt + len > s.input.length) {
// Not enough input
return ErrorCode.ERR_NOT_TERMINATED;
}
if (s.outcnt + len > s.output.length) {
// Not enough output space
return ErrorCode.ERR_OUTPUT_EXHAUSTED;
}
while (len != 0) {
// Note: Solidity reverts on underflow, so we decrement here
len -= 1;
s.output[s.outcnt++] = s.input[s.incnt++];
}
// Done with a valid stored block
return ErrorCode.ERR_NONE;
}
function _decode(State memory s, Huffman memory h)
private
pure
returns (ErrorCode, uint256)
{
// Current number of bits in code
uint256 len;
// Len bits being decoded
uint256 code = 0;
// First code of length len
uint256 first = 0;
// Number of codes of length len
uint256 count;
// Index of first code of length len in symbol table
uint256 index = 0;
// Error code
ErrorCode err;
for (len = 1; len <= MAXBITS; len++) {
// Get next bit
uint256 tempCode;
(err, tempCode) = bits(s, 1);
if (err != ErrorCode.ERR_NONE) {
return (err, 0);
}
code |= tempCode;
count = h.counts[len];
// If length len, return symbol
if (code < first + count) {
return (ErrorCode.ERR_NONE, h.symbols[index + (code - first)]);
}
// Else update for next length
index += count;
first += count;
first <<= 1;
code <<= 1;
}
// Ran out of codes
return (ErrorCode.ERR_INVALID_LENGTH_OR_DISTANCE_CODE, 0);
}
function _construct(
Huffman memory h,
uint256[] memory lengths,
uint256 n,
uint256 start
) private pure returns (ErrorCode) {
// Current symbol when stepping through lengths[]
uint256 symbol;
// Current length when stepping through h.counts[]
uint256 len;
// Number of possible codes left of current length
uint256 left;
// Offsets in symbol table for each length
uint256[MAXBITS + 1] memory offs;
// Count number of codes of each length
for (len = 0; len <= MAXBITS; len++) {
h.counts[len] = 0;
}
for (symbol = 0; symbol < n; symbol++) {
// Assumes lengths are within bounds
h.counts[lengths[start + symbol]]++;
}
// No codes!
if (h.counts[0] == n) {
// Complete, but decode() will fail
return (ErrorCode.ERR_NONE);
}
// Check for an over-subscribed or incomplete set of lengths
// One possible code of zero length
left = 1;
for (len = 1; len <= MAXBITS; len++) {
// One more bit, double codes left
left <<= 1;
if (left < h.counts[len]) {
// Over-subscribed--return error
return ErrorCode.ERR_CONSTRUCT;
}
// Deduct count from possible codes
left -= h.counts[len];
}
// Generate offsets into symbol table for each length for sorting
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + h.counts[len];
}
// Put symbols in table sorted by length, by symbol order within each length
for (symbol = 0; symbol < n; symbol++) {
if (lengths[start + symbol] != 0) {
h.symbols[offs[lengths[start + symbol]]++] = symbol;
}
}
// Left > 0 means incomplete
return left > 0 ? ErrorCode.ERR_CONSTRUCT : ErrorCode.ERR_NONE;
}
function _codes(
State memory s,
Huffman memory lencode,
Huffman memory distcode
) private pure returns (ErrorCode) {
// Decoded symbol
uint256 symbol;
// Length for copy
uint256 len;
// Distance for copy
uint256 dist;
// TODO Solidity doesn't support constant arrays, but these are fixed at compile-time
// Size base for length codes 257..285
uint16[29] memory lens =
[
3,
4,
5,
6,
7,
8,
9,
10,
11,
13,
15,
17,
19,
23,
27,
31,
35,
43,
51,
59,
67,
83,
99,
115,
131,
163,
195,
227,
258
];
// Extra bits for length codes 257..285
uint8[29] memory lext =
[
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
2,
2,
2,
2,
3,
3,
3,
3,
4,
4,
4,
4,
5,
5,
5,
5,
0
];
// Offset base for distance codes 0..29
uint16[30] memory dists =
[
1,
2,
3,
4,
5,
7,
9,
13,
17,
25,
33,
49,
65,
97,
129,
193,
257,
385,
513,
769,
1025,
1537,
2049,
3073,
4097,
6145,
8193,
12289,
16385,
24577
];
// Extra bits for distance codes 0..29
uint8[30] memory dext =
[
0,
0,
0,
0,
1,
1,
2,
2,
3,
3,
4,
4,
5,
5,
6,
6,
7,
7,
8,
8,
9,
9,
10,
10,
11,
11,
12,
12,
13,
13
];
// Error code
ErrorCode err;
// Decode literals and length/distance pairs
while (symbol != 256) {
(err, symbol) = _decode(s, lencode);
if (err != ErrorCode.ERR_NONE) {
// Invalid symbol
return err;
}
if (symbol < 256) {
// Literal: symbol is the byte
// Write out the literal
if (s.outcnt == s.output.length) {
return ErrorCode.ERR_OUTPUT_EXHAUSTED;
}
s.output[s.outcnt] = bytes1(uint8(symbol));
s.outcnt++;
} else if (symbol > 256) {
uint256 tempBits;
// Length
// Get and compute length
symbol -= 257;
if (symbol >= 29) {
// Invalid fixed code
return ErrorCode.ERR_INVALID_LENGTH_OR_DISTANCE_CODE;
}
(err, tempBits) = bits(s, lext[symbol]);
if (err != ErrorCode.ERR_NONE) {
return err;
}
len = lens[symbol] + tempBits;
// Get and check distance
(err, symbol) = _decode(s, distcode);
if (err != ErrorCode.ERR_NONE) {
// Invalid symbol
return err;
}
(err, tempBits) = bits(s, dext[symbol]);
if (err != ErrorCode.ERR_NONE) {
return err;
}
dist = dists[symbol] + tempBits;
if (dist > s.outcnt) {
// Distance too far back
return ErrorCode.ERR_DISTANCE_TOO_FAR;
}
// Copy length bytes from distance bytes back
if (s.outcnt + len > s.output.length) {
return ErrorCode.ERR_OUTPUT_EXHAUSTED;
}
while (len != 0) {
// Note: Solidity reverts on underflow, so we decrement here
len -= 1;
s.output[s.outcnt] = s.output[s.outcnt - dist];
s.outcnt++;
}
} else {
s.outcnt += len;
}
}
// Done with a valid fixed or dynamic block
return ErrorCode.ERR_NONE;
}
function _build_fixed(State memory s) private pure returns (ErrorCode) {
// Build fixed Huffman tables
// TODO this is all a compile-time constant
uint256 symbol;
uint256[] memory lengths = new uint256[](FIXLCODES);
// Literal/length table
for (symbol = 0; symbol < 144; symbol++) {
lengths[symbol] = 8;
}
for (; symbol < 256; symbol++) {
lengths[symbol] = 9;
}
for (; symbol < 280; symbol++) {
lengths[symbol] = 7;
}
for (; symbol < FIXLCODES; symbol++) {
lengths[symbol] = 8;
}
_construct(s.lencode, lengths, FIXLCODES, 0);
// Distance table
for (symbol = 0; symbol < MAXDCODES; symbol++) {
lengths[symbol] = 5;
}
_construct(s.distcode, lengths, MAXDCODES, 0);
return ErrorCode.ERR_NONE;
}
function _fixed(State memory s) private pure returns (ErrorCode) {
// Decode data until end-of-block code
return _codes(s, s.lencode, s.distcode);
}
function _build_dynamic_lengths(State memory s)
private
pure
returns (ErrorCode, uint256[] memory)
{
uint256 ncode;
// Index of lengths[]
uint256 index;
// Descriptor code lengths
uint256[] memory lengths = new uint256[](MAXCODES);
// Error code
ErrorCode err;
// Permutation of code length codes
uint8[19] memory order =
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
(err, ncode) = bits(s, 4);
if (err != ErrorCode.ERR_NONE) {
return (err, lengths);
}
ncode += 4;
// Read code length code lengths (really), missing lengths are zero
for (index = 0; index < ncode; index++) {
(err, lengths[order[index]]) = bits(s, 3);
if (err != ErrorCode.ERR_NONE) {
return (err, lengths);
}
}
for (; index < 19; index++) {
lengths[order[index]] = 0;
}
return (ErrorCode.ERR_NONE, lengths);
}
function _build_dynamic(State memory s)
private
pure
returns (
ErrorCode,
Huffman memory,
Huffman memory
)
{
// Number of lengths in descriptor
uint256 nlen;
uint256 ndist;
// Index of lengths[]
uint256 index;
// Error code
ErrorCode err;
// Descriptor code lengths
uint256[] memory lengths = new uint256[](MAXCODES);
// Length and distance codes
Huffman memory lencode =
Huffman(new uint256[](MAXBITS + 1), new uint256[](MAXLCODES));
Huffman memory distcode =
Huffman(new uint256[](MAXBITS + 1), new uint256[](MAXDCODES));
uint256 tempBits;
// Get number of lengths in each table, check lengths
(err, nlen) = bits(s, 5);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
nlen += 257;
(err, ndist) = bits(s, 5);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
ndist += 1;
if (nlen > MAXLCODES || ndist > MAXDCODES) {
// Bad counts
return (
ErrorCode.ERR_TOO_MANY_LENGTH_OR_DISTANCE_CODES,
lencode,
distcode
);
}
(err, lengths) = _build_dynamic_lengths(s);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
// Build huffman table for code lengths codes (use lencode temporarily)
err = _construct(lencode, lengths, 19, 0);
if (err != ErrorCode.ERR_NONE) {
// Require complete code set here
return (
ErrorCode.ERR_CODE_LENGTHS_CODES_INCOMPLETE,
lencode,
distcode
);
}
// Read length/literal and distance code length tables
index = 0;
while (index < nlen + ndist) {
// Decoded value
uint256 symbol;
// Last length to repeat
uint256 len;
(err, symbol) = _decode(s, lencode);
if (err != ErrorCode.ERR_NONE) {
// Invalid symbol
return (err, lencode, distcode);
}
if (symbol < 16) {
// Length in 0..15
lengths[index++] = symbol;
} else {
// Repeat instruction
// Assume repeating zeros
len = 0;
if (symbol == 16) {
// Repeat last length 3..6 times
if (index == 0) {
// No last length!
return (
ErrorCode.ERR_REPEAT_NO_FIRST_LENGTH,
lencode,
distcode
);
}
// Last length
len = lengths[index - 1];
(err, tempBits) = bits(s, 2);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
symbol = 3 + tempBits;
} else if (symbol == 17) {
// Repeat zero 3..10 times
(err, tempBits) = bits(s, 3);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
symbol = 3 + tempBits;
} else {
// == 18, repeat zero 11..138 times
(err, tempBits) = bits(s, 7);
if (err != ErrorCode.ERR_NONE) {
return (err, lencode, distcode);
}
symbol = 11 + tempBits;
}
if (index + symbol > nlen + ndist) {
// Too many lengths!
return (ErrorCode.ERR_REPEAT_MORE, lencode, distcode);
}
while (symbol != 0) {
// Note: Solidity reverts on underflow, so we decrement here
symbol -= 1;
// Repeat last or zero symbol times
lengths[index++] = len;
}
}
}
// Check for end-of-block code -- there better be one!
if (lengths[256] == 0) {
return (ErrorCode.ERR_MISSING_END_OF_BLOCK, lencode, distcode);
}
// Build huffman table for literal/length codes
err = _construct(lencode, lengths, nlen, 0);
if (
err != ErrorCode.ERR_NONE &&
(err == ErrorCode.ERR_NOT_TERMINATED ||
err == ErrorCode.ERR_OUTPUT_EXHAUSTED ||
nlen != lencode.counts[0] + lencode.counts[1])
) {
// Incomplete code ok only for single length 1 code
return (
ErrorCode.ERR_INVALID_LITERAL_LENGTH_CODE_LENGTHS,
lencode,
distcode
);
}
// Build huffman table for distance codes
err = _construct(distcode, lengths, ndist, nlen);
if (
err != ErrorCode.ERR_NONE &&
(err == ErrorCode.ERR_NOT_TERMINATED ||
err == ErrorCode.ERR_OUTPUT_EXHAUSTED ||
ndist != distcode.counts[0] + distcode.counts[1])
) {
// Incomplete code ok only for single length 1 code
return (
ErrorCode.ERR_INVALID_DISTANCE_CODE_LENGTHS,
lencode,
distcode
);
}
return (ErrorCode.ERR_NONE, lencode, distcode);
}
function _dynamic(State memory s) private pure returns (ErrorCode) {
// Length and distance codes
Huffman memory lencode;
Huffman memory distcode;
// Error code
ErrorCode err;
(err, lencode, distcode) = _build_dynamic(s);
if (err != ErrorCode.ERR_NONE) {
return err;
}
// Decode data until end-of-block code
return _codes(s, lencode, distcode);
}
function puff(bytes calldata source, uint256 destlen)
internal
pure
returns (ErrorCode, bytes memory)
{
// Input/output state
State memory s =
State(
new bytes(destlen),
0,
source,
0,
0,
0,
Huffman(new uint256[](MAXBITS + 1), new uint256[](FIXLCODES)),
Huffman(new uint256[](MAXBITS + 1), new uint256[](MAXDCODES))
);
// Temp: last bit
uint256 last;
// Temp: block type bit
uint256 t;
// Error code
ErrorCode err;
// Build fixed Huffman tables
err = _build_fixed(s);
if (err != ErrorCode.ERR_NONE) {
return (err, s.output);
}
// Process blocks until last block or error
while (last == 0) {
// One if last block
(err, last) = bits(s, 1);
if (err != ErrorCode.ERR_NONE) {
return (err, s.output);
}
// Block type 0..3
(err, t) = bits(s, 2);
if (err != ErrorCode.ERR_NONE) {
return (err, s.output);
}
err = (
t == 0
? _stored(s)
: (
t == 1
? _fixed(s)
: (
t == 2
? _dynamic(s)
: ErrorCode.ERR_INVALID_BLOCK_TYPE
)
)
);
// type == 3, invalid
if (err != ErrorCode.ERR_NONE) {
// Return with error
break;
}
}
return (err, s.output);
}
}
| 2,000 |
9 | // The owner of the Paymaster can change the instance of the RelayHub this Paymaster works with.:warning: Warning :warning: The deposit on the previous RelayHub must be withdrawn first. / | function setRelayHub(IRelayHub hub) public onlyOwner {
require(address(hub).supportsInterface(type(IRelayHub).interfaceId), "target is not a valid IRelayHub");
relayHub = hub;
}
| function setRelayHub(IRelayHub hub) public onlyOwner {
require(address(hub).supportsInterface(type(IRelayHub).interfaceId), "target is not a valid IRelayHub");
relayHub = hub;
}
| 23,677 |
5 | // // USER FUNCTIONS /// | function publicSaleRemainingCount() public view returns (uint256) {
uint256 totalWhiteListRemainingCount = firstWhiteListSaleRemainingCount +
secondWhiteListSaleRemainingCount;
return
publicSalePurchasedCount <= totalWhiteListRemainingCount
? totalWhiteListRemainingCount - publicSalePurchasedCount
: 0;
}
| function publicSaleRemainingCount() public view returns (uint256) {
uint256 totalWhiteListRemainingCount = firstWhiteListSaleRemainingCount +
secondWhiteListSaleRemainingCount;
return
publicSalePurchasedCount <= totalWhiteListRemainingCount
? totalWhiteListRemainingCount - publicSalePurchasedCount
: 0;
}
| 47,611 |
13 | // each one box is entitled to every pair of the socks so if boxIds.length = n, then we mint 3n pairs of socks | amounts[0] = boxIdsLength;
amounts[1] = boxIdsLength;
amounts[2] = boxIdsLength;
STANCE_RKL_COLLECTION.mint(msg.sender, SOX_TRIPLET, amounts);
| amounts[0] = boxIdsLength;
amounts[1] = boxIdsLength;
amounts[2] = boxIdsLength;
STANCE_RKL_COLLECTION.mint(msg.sender, SOX_TRIPLET, amounts);
| 4,619 |
14 | // Emitted when a new Connext address is set connext The new connext address / | event SetConnext(address indexed connext);
| event SetConnext(address indexed connext);
| 12,247 |
46 | // sweeps any ammount of tokens / | function sweepMany(address[] memory _erc20sToSweep) public {
for(uint i = 0; i < _erc20sToSweep.length; i++){
sweepERC20(_erc20sToSweep[i]);
}
}
| function sweepMany(address[] memory _erc20sToSweep) public {
for(uint i = 0; i < _erc20sToSweep.length; i++){
sweepERC20(_erc20sToSweep[i]);
}
}
| 14,871 |
142 | // Hook that is called before any token transfer. This includes mintingand burning. Calling conditions: - When `from` and `to` are both non-zero, ``from``'s `tokenId` will betransferred 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.adocusing-hooks[Using Hooks]. / | function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
| function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
| 3,041 |
7 | // MIN_AMOUNT_FOR_NEW_CLONE is the minimum amount for a clone | dm.duplicate(nftAddr, nftId, currencyAddr, 1, false, 0);
vm.expectRevert(abi.encodeWithSelector(DittoMachine.InvalidFloorId.selector));
dm.duplicate(nftAddr, nftId, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE, true, 0);
vm.stopPrank();
| dm.duplicate(nftAddr, nftId, currencyAddr, 1, false, 0);
vm.expectRevert(abi.encodeWithSelector(DittoMachine.InvalidFloorId.selector));
dm.duplicate(nftAddr, nftId, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE, true, 0);
vm.stopPrank();
| 45,693 |
10 | // Use Identity (0x04) precompile to memcpy the base | if iszero(staticcall(10000, 0x04, add(base, 0x20), bl, add(p, 0x60), bl)) {
revert(0, 0)
}
| if iszero(staticcall(10000, 0x04, add(base, 0x20), bl, add(p, 0x60), bl)) {
revert(0, 0)
}
| 20,615 |
22 | // See {ICreatorCore-setBaseTokenURI}. / | function setBaseTokenURI(string calldata uri_) external override adminRequired {
_setBaseTokenURI(uri_);
}
| function setBaseTokenURI(string calldata uri_) external override adminRequired {
_setBaseTokenURI(uri_);
}
| 32,399 |
29 | // Get token contract for item. | address token = address(getTokenToBurnItem(itemId));
| address token = address(getTokenToBurnItem(itemId));
| 5,994 |
167 | // mint the difference only to MC, update mintReward | mintReward = mint.maxSupply().sub(mint.totalSupply());
mint.mint(address(this), mintReward);
| mintReward = mint.maxSupply().sub(mint.totalSupply());
mint.mint(address(this), mintReward);
| 1,559 |
130 | // user should already have shares here, let's increment | vaultUsers[_user].vaultShares += previewDepositEpoch(
vaultUsers[_user].assetsDeposited,
vaultUsers[_user].epochLastDeposited + 1
);
vaultUsers[_user].assetsDeposited = 0;
vaultUsers[_user].epochLastDeposited = 0;
| vaultUsers[_user].vaultShares += previewDepositEpoch(
vaultUsers[_user].assetsDeposited,
vaultUsers[_user].epochLastDeposited + 1
);
vaultUsers[_user].assetsDeposited = 0;
vaultUsers[_user].epochLastDeposited = 0;
| 3,302 |
10 | // This is the code that is executed after `simpleFlashLoan` initiated the flash-borrowWhen this code executes, this contract will hold the flash-borrowed _amount of _tokenBorrow | function simpleFlashLoanExecute(
address _tokenBorrow,
uint _amount,
address _pairAddress,
bool _isBorrowingEth,
bool _isPayingEth,
bytes memory _userData
| function simpleFlashLoanExecute(
address _tokenBorrow,
uint _amount,
address _pairAddress,
bool _isBorrowingEth,
bool _isPayingEth,
bytes memory _userData
| 17,895 |
100 | // updates list of supported tokens, it can be use also to disable or enable particualr token/addrs array of address of pools/toggles array of addresses of assets/withApprovals resets tokens to unlimited approval with the swaps integration (kyber, etc.) | function setSupportedTokens(
address[] calldata addrs,
bool[] calldata toggles,
bool withApprovals
) external;
| function setSupportedTokens(
address[] calldata addrs,
bool[] calldata toggles,
bool withApprovals
) external;
| 40,158 |
457 | // updates the state of the user as a consequence of a swap rate action._reserve the address of the reserve on which the user is performing the swap_user the address of the borrower_balanceIncrease the accrued interest on the borrowed amount_currentRateMode the current rate mode of the user/ | ) internal returns (CoreLibrary.InterestRateMode) {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.InterestRateMode newMode = CoreLibrary.InterestRateMode.NONE;
if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
//switch to stable
newMode = CoreLibrary.InterestRateMode.STABLE;
user.stableBorrowRate = reserve.currentStableBorrowRate;
user.lastVariableBorrowCumulativeIndex = 0;
} else if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) {
newMode = CoreLibrary.InterestRateMode.VARIABLE;
user.stableBorrowRate = 0;
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
} else {
revert("Invalid interest rate mode received");
}
//compounding cumulated interest
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease);
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
return newMode;
}
| ) internal returns (CoreLibrary.InterestRateMode) {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.InterestRateMode newMode = CoreLibrary.InterestRateMode.NONE;
if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
//switch to stable
newMode = CoreLibrary.InterestRateMode.STABLE;
user.stableBorrowRate = reserve.currentStableBorrowRate;
user.lastVariableBorrowCumulativeIndex = 0;
} else if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) {
newMode = CoreLibrary.InterestRateMode.VARIABLE;
user.stableBorrowRate = 0;
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
} else {
revert("Invalid interest rate mode received");
}
//compounding cumulated interest
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease);
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
return newMode;
}
| 32,169 |
24 | // Yields the excess beyond the floor of x./Based on the odd function definition https:en.wikipedia.org/wiki/Fractional_part./x The unsigned 60.18-decimal fixed-point number to get the fractional part of./result The fractional part of x as an unsigned 60.18-decimal fixed-point number. | function frac(uint256 x) internal pure returns (uint256 result) {
assembly {
result := mod(x, SCALE)
}
}
| function frac(uint256 x) internal pure returns (uint256 result) {
assembly {
result := mod(x, SCALE)
}
}
| 23,383 |
18 | // / | function getTokenData(uint256 tokenId, uint256 index) public view returns (string memory _tokenHash, string memory _tokenType) {
require(_exists(tokenId), "Token does not exist.");
uint256 tokenBatchRef = referenceTotokenBatch[tokenId];
_tokenHash = tokenBatch[tokenBatchRef][index];
_tokenType = tokenType[tokenBatchRef][index];
}
| function getTokenData(uint256 tokenId, uint256 index) public view returns (string memory _tokenHash, string memory _tokenType) {
require(_exists(tokenId), "Token does not exist.");
uint256 tokenBatchRef = referenceTotokenBatch[tokenId];
_tokenHash = tokenBatch[tokenBatchRef][index];
_tokenType = tokenType[tokenBatchRef][index];
}
| 24,865 |
49 | // storing the protocol fee | execution.sellProtocolFee = protocolFee;
| execution.sellProtocolFee = protocolFee;
| 17,726 |
191 | // Concatenate the tokenID to the baseURI. | return string(abi.encodePacked(_baseTokenURI, tokenId.toString()));
| return string(abi.encodePacked(_baseTokenURI, tokenId.toString()));
| 57,407 |
0 | // IReserveInterestRateStrategyInterface interface Interface for the calculation of the interest rates Aave / | interface IReserveInterestRateStrategy {
function baseVariableBorrowRate() external view returns (uint256);
function getMaxVariableBorrowRate() external view returns (uint256);
function calculateInterestRates(
address reserve,
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
external
view
returns (
uint256,
uint256,
uint256
);
function calculateInterestRates(
address reserve,
address aToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
external
view
returns (
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate
);
}
| interface IReserveInterestRateStrategy {
function baseVariableBorrowRate() external view returns (uint256);
function getMaxVariableBorrowRate() external view returns (uint256);
function calculateInterestRates(
address reserve,
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
external
view
returns (
uint256,
uint256,
uint256
);
function calculateInterestRates(
address reserve,
address aToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
external
view
returns (
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate
);
}
| 28,818 |
186 | // Look up information about a specific tick in the pool/tick The tick to look up/ return liquidityGross total liquidity amount from positions that uses this tick as a lower or upper tick/ liquidityNet how much liquidity changes when the pool tick crosses above the tick/ feeGrowthOutside the fee growth on the other side of the tick relative to the current tick/ secondsPerLiquidityOutside the seconds per unit of liquidityspent on the other side of the tick relative to the current tick | function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside,
uint128 secondsPerLiquidityOutside
);
| function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside,
uint128 secondsPerLiquidityOutside
);
| 30,857 |
202 | // underflow attempts BTFO | SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_**2 - tokens_) / 1e18)) / 2
)
/ 1e18);
| SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_**2 - tokens_) / 1e18)) / 2
)
/ 1e18);
| 21,560 |
89 | // Distribute tokens to farm in linear fashion based on time / | function distribute() public override {
// cannot distribute until distribution start
uint256 amount = nextDistribution();
if (amount == 0) {
return;
}
// transfer tokens & update state
lastDistribution = block.timestamp;
distributed = distributed.add(amount);
trustToken.safeTransfer(farm, amount);
emit Distributed(amount);
}
| function distribute() public override {
// cannot distribute until distribution start
uint256 amount = nextDistribution();
if (amount == 0) {
return;
}
// transfer tokens & update state
lastDistribution = block.timestamp;
distributed = distributed.add(amount);
trustToken.safeTransfer(farm, amount);
emit Distributed(amount);
}
| 78,322 |
155 | // Only maintain 1e6 resolution. | newInfo = info & ~(((U256_1 << 20) - 1) << 160);
newInfo = newInfo | ((w / 1e12) << 160);
| newInfo = info & ~(((U256_1 << 20) - 1) << 160);
newInfo = newInfo | ((w / 1e12) << 160);
| 18,555 |
168 | // Distribute the `tRewardFee` tokens to all holders that are included in receiving reward.amount received is based on how many token one owns. / | function _distributeFee(uint256 rRewardFee, uint256 tRewardFee) private {
// This would decrease rate, thus increase amount reward receive based on one's balance.
_reflectionTotal = _reflectionTotal - rRewardFee;
_totalRewarded += tRewardFee;
}
| function _distributeFee(uint256 rRewardFee, uint256 tRewardFee) private {
// This would decrease rate, thus increase amount reward receive based on one's balance.
_reflectionTotal = _reflectionTotal - rRewardFee;
_totalRewarded += tRewardFee;
}
| 18,952 |
27 | // Proxy Proxy is a transparent proxy that passes through the call if the caller is the owner orif the caller is address(0), meaning that the call originated from an off-chainsimulation. / | contract Proxy {
/**
* @notice The storage slot that holds the address of the implementation.
* bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
*/
bytes32 internal constant IMPLEMENTATION_KEY =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @notice The storage slot that holds the address of the owner.
* bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)
*/
bytes32 internal constant OWNER_KEY =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @notice An event that is emitted each time the implementation is changed. This event is part
* of the EIP-1967 specification.
*
* @param implementation The address of the implementation contract
*/
event Upgraded(address indexed implementation);
/**
* @notice An event that is emitted each time the owner is upgraded. This event is part of the
* EIP-1967 specification.
*
* @param previousAdmin The previous owner of the contract
* @param newAdmin The new owner of the contract
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @notice A modifier that reverts if not called by the owner or by address(0) to allow
* eth_call to interact with this proxy without needing to use low-level storage
* inspection. We assume that nobody is able to trigger calls from address(0) during
* normal EVM execution.
*/
modifier proxyCallIfNotAdmin() {
if (msg.sender == _getAdmin() || msg.sender == address(0)) {
_;
} else {
// This WILL halt the call frame on completion.
_doProxyCall();
}
}
/**
* @notice Sets the initial admin during contract deployment. Admin address is stored at the
* EIP-1967 admin storage slot so that accidental storage collision with the
* implementation is not possible.
*
* @param _admin Address of the initial contract admin. Admin as the ability to access the
* transparent proxy interface.
*/
constructor(address _admin) {
_changeAdmin(_admin);
}
// slither-disable-next-line locked-ether
receive() external payable {
// Proxy call by default.
_doProxyCall();
}
// slither-disable-next-line locked-ether
fallback() external payable {
// Proxy call by default.
_doProxyCall();
}
/**
* @notice Set the implementation contract address. The code at the given address will execute
* when this contract is called.
*
* @param _implementation Address of the implementation contract.
*/
function upgradeTo(address _implementation) public virtual proxyCallIfNotAdmin {
_setImplementation(_implementation);
}
/**
* @notice Set the implementation and call a function in a single transaction. Useful to ensure
* atomic execution of initialization-based upgrades.
*
* @param _implementation Address of the implementation contract.
* @param _data Calldata to delegatecall the new implementation with.
*/
function upgradeToAndCall(
address _implementation,
bytes calldata _data
) public payable virtual proxyCallIfNotAdmin returns (bytes memory) {
_setImplementation(_implementation);
(bool success, bytes memory returndata) = _implementation.delegatecall(_data);
require(success, "Proxy: delegatecall to new implementation contract failed");
return returndata;
}
/**
* @notice Changes the owner of the proxy contract. Only callable by the owner.
*
* @param _admin New owner of the proxy contract.
*/
function changeAdmin(address _admin) public virtual proxyCallIfNotAdmin {
_changeAdmin(_admin);
}
/**
* @notice Gets the owner of the proxy contract.
*
* @return Owner address.
*/
function admin() public virtual proxyCallIfNotAdmin returns (address) {
return _getAdmin();
}
/**
* @notice Queries the implementation address.
*
* @return Implementation address.
*/
function implementation() public virtual proxyCallIfNotAdmin returns (address) {
return _getImplementation();
}
/**
* @notice Sets the implementation address.
*
* @param _implementation New implementation address.
*/
function _setImplementation(address _implementation) internal {
assembly {
sstore(IMPLEMENTATION_KEY, _implementation)
}
emit Upgraded(_implementation);
}
/**
* @notice Changes the owner of the proxy contract.
*
* @param _admin New owner of the proxy contract.
*/
function _changeAdmin(address _admin) internal {
address previous = _getAdmin();
assembly {
sstore(OWNER_KEY, _admin)
}
emit AdminChanged(previous, _admin);
}
/**
* @notice Performs the proxy call via a delegatecall.
*/
function _doProxyCall() internal {
address impl = _getImplementation();
require(impl != address(0), "Proxy: implementation not initialized");
assembly {
// Copy calldata into memory at 0x0....calldatasize.
calldatacopy(0x0, 0x0, calldatasize())
// Perform the delegatecall, make sure to pass all available gas.
let success := delegatecall(gas(), impl, 0x0, calldatasize(), 0x0, 0x0)
// Copy returndata into memory at 0x0....returndatasize. Note that this *will*
// overwrite the calldata that we just copied into memory but that doesn't really
// matter because we'll be returning in a second anyway.
returndatacopy(0x0, 0x0, returndatasize())
// Success == 0 means a revert. We'll revert too and pass the data up.
if iszero(success) {
revert(0x0, returndatasize())
}
// Otherwise we'll just return and pass the data up.
return(0x0, returndatasize())
}
}
/**
* @notice Queries the implementation address.
*
* @return Implementation address.
*/
function _getImplementation() internal view returns (address) {
address impl;
assembly {
impl := sload(IMPLEMENTATION_KEY)
}
return impl;
}
/**
* @notice Queries the owner of the proxy contract.
*
* @return Owner address.
*/
function _getAdmin() internal view returns (address) {
address owner;
assembly {
owner := sload(OWNER_KEY)
}
return owner;
}
}
| contract Proxy {
/**
* @notice The storage slot that holds the address of the implementation.
* bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
*/
bytes32 internal constant IMPLEMENTATION_KEY =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @notice The storage slot that holds the address of the owner.
* bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)
*/
bytes32 internal constant OWNER_KEY =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @notice An event that is emitted each time the implementation is changed. This event is part
* of the EIP-1967 specification.
*
* @param implementation The address of the implementation contract
*/
event Upgraded(address indexed implementation);
/**
* @notice An event that is emitted each time the owner is upgraded. This event is part of the
* EIP-1967 specification.
*
* @param previousAdmin The previous owner of the contract
* @param newAdmin The new owner of the contract
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @notice A modifier that reverts if not called by the owner or by address(0) to allow
* eth_call to interact with this proxy without needing to use low-level storage
* inspection. We assume that nobody is able to trigger calls from address(0) during
* normal EVM execution.
*/
modifier proxyCallIfNotAdmin() {
if (msg.sender == _getAdmin() || msg.sender == address(0)) {
_;
} else {
// This WILL halt the call frame on completion.
_doProxyCall();
}
}
/**
* @notice Sets the initial admin during contract deployment. Admin address is stored at the
* EIP-1967 admin storage slot so that accidental storage collision with the
* implementation is not possible.
*
* @param _admin Address of the initial contract admin. Admin as the ability to access the
* transparent proxy interface.
*/
constructor(address _admin) {
_changeAdmin(_admin);
}
// slither-disable-next-line locked-ether
receive() external payable {
// Proxy call by default.
_doProxyCall();
}
// slither-disable-next-line locked-ether
fallback() external payable {
// Proxy call by default.
_doProxyCall();
}
/**
* @notice Set the implementation contract address. The code at the given address will execute
* when this contract is called.
*
* @param _implementation Address of the implementation contract.
*/
function upgradeTo(address _implementation) public virtual proxyCallIfNotAdmin {
_setImplementation(_implementation);
}
/**
* @notice Set the implementation and call a function in a single transaction. Useful to ensure
* atomic execution of initialization-based upgrades.
*
* @param _implementation Address of the implementation contract.
* @param _data Calldata to delegatecall the new implementation with.
*/
function upgradeToAndCall(
address _implementation,
bytes calldata _data
) public payable virtual proxyCallIfNotAdmin returns (bytes memory) {
_setImplementation(_implementation);
(bool success, bytes memory returndata) = _implementation.delegatecall(_data);
require(success, "Proxy: delegatecall to new implementation contract failed");
return returndata;
}
/**
* @notice Changes the owner of the proxy contract. Only callable by the owner.
*
* @param _admin New owner of the proxy contract.
*/
function changeAdmin(address _admin) public virtual proxyCallIfNotAdmin {
_changeAdmin(_admin);
}
/**
* @notice Gets the owner of the proxy contract.
*
* @return Owner address.
*/
function admin() public virtual proxyCallIfNotAdmin returns (address) {
return _getAdmin();
}
/**
* @notice Queries the implementation address.
*
* @return Implementation address.
*/
function implementation() public virtual proxyCallIfNotAdmin returns (address) {
return _getImplementation();
}
/**
* @notice Sets the implementation address.
*
* @param _implementation New implementation address.
*/
function _setImplementation(address _implementation) internal {
assembly {
sstore(IMPLEMENTATION_KEY, _implementation)
}
emit Upgraded(_implementation);
}
/**
* @notice Changes the owner of the proxy contract.
*
* @param _admin New owner of the proxy contract.
*/
function _changeAdmin(address _admin) internal {
address previous = _getAdmin();
assembly {
sstore(OWNER_KEY, _admin)
}
emit AdminChanged(previous, _admin);
}
/**
* @notice Performs the proxy call via a delegatecall.
*/
function _doProxyCall() internal {
address impl = _getImplementation();
require(impl != address(0), "Proxy: implementation not initialized");
assembly {
// Copy calldata into memory at 0x0....calldatasize.
calldatacopy(0x0, 0x0, calldatasize())
// Perform the delegatecall, make sure to pass all available gas.
let success := delegatecall(gas(), impl, 0x0, calldatasize(), 0x0, 0x0)
// Copy returndata into memory at 0x0....returndatasize. Note that this *will*
// overwrite the calldata that we just copied into memory but that doesn't really
// matter because we'll be returning in a second anyway.
returndatacopy(0x0, 0x0, returndatasize())
// Success == 0 means a revert. We'll revert too and pass the data up.
if iszero(success) {
revert(0x0, returndatasize())
}
// Otherwise we'll just return and pass the data up.
return(0x0, returndatasize())
}
}
/**
* @notice Queries the implementation address.
*
* @return Implementation address.
*/
function _getImplementation() internal view returns (address) {
address impl;
assembly {
impl := sload(IMPLEMENTATION_KEY)
}
return impl;
}
/**
* @notice Queries the owner of the proxy contract.
*
* @return Owner address.
*/
function _getAdmin() internal view returns (address) {
address owner;
assembly {
owner := sload(OWNER_KEY)
}
return owner;
}
}
| 31,012 |
124 | // STORAGE UPDATE 1 | EverscaleAddress configurationAlien_;
| EverscaleAddress configurationAlien_;
| 64,342 |
8 | // Update user name. |
if (users[msg.sender].name != 0x0)
{
users[msg.sender].name = name;
return (users[msg.sender].name);
}
|
if (users[msg.sender].name != 0x0)
{
users[msg.sender].name = name;
return (users[msg.sender].name);
}
| 49,779 |
139 | // verify if sessionPubkeyHash was verified already, if not.. let's do it! | if (provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = provable_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
| if (provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = provable_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
| 5,579 |
4 | // Allowance amounts on behalf of others | mapping(address => mapping(address => uint)) internal allowances;
| mapping(address => mapping(address => uint)) internal allowances;
| 65,939 |
11 | // Sweep any ERC20 token.Sometimes people accidentally send tokens to a contract without any way to retrieve them.This contract makes sure any erc20 tokens can be removed from the contract. / | contract SweeperUpgradeable is OwnableUpgradeable {
struct NFT {
IERC721 nftaddress;
uint256[] ids;
}
mapping(address => bool) public lockedTokens;
bool public allowNativeSweep;
event SweepWithdrawToken(
address indexed receiver,
IERC20 indexed token,
uint256 balance
);
event SweepWithdrawNFTs(address indexed receiver, NFT[] indexed nfts);
event SweepWithdrawNative(address indexed receiver, uint256 balance);
/**
* @dev Transfers erc20 tokens to owner
* Only owner of contract can call this function
*/
function sweepTokens(IERC20[] memory tokens, address to) public onlyOwner {
NFT[] memory empty;
sweepTokensAndNFTs(tokens, empty, to);
}
/**
* @dev Transfers NFT to owner
* Only owner of contract can call this function
*/
function sweepNFTs(NFT[] memory nfts, address to) public onlyOwner {
IERC20[] memory empty;
sweepTokensAndNFTs(empty, nfts, to);
}
/**
* @dev Transfers ERC20 and NFT to owner
* Only owner of contract can call this function
*/
function sweepTokensAndNFTs(
IERC20[] memory tokens,
NFT[] memory nfts,
address to
) public onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
IERC20 token = tokens[i];
require(!lockedTokens[address(token)], "Tokens can't be swept");
uint256 balance = token.balanceOf(address(this));
token.transfer(to, balance);
emit SweepWithdrawToken(to, token, balance);
}
for (uint256 i = 0; i < nfts.length; i++) {
IERC721 nftaddress = nfts[i].nftaddress;
require(
!lockedTokens[address(nftaddress)],
"Tokens can't be swept"
);
uint256[] memory ids = nfts[i].ids;
for (uint256 j = 0; j < ids.length; j++) {
nftaddress.safeTransferFrom(address(this), to, ids[j]);
}
}
emit SweepWithdrawNFTs(to, nfts);
}
/// @notice Sweep native coin
/// @param _to address the native coins should be transferred to
function sweepNative(address payable _to) public onlyOwner {
require(allowNativeSweep, "Not allowed");
uint256 balance = address(this).balance;
_to.transfer(balance);
emit SweepWithdrawNative(_to, balance);
}
/**
* @dev Refuse native sweep.
* Once refused can't be allowed again
*/
function refuseNativeSweep() public onlyOwner {
allowNativeSweep = false;
}
/**
* @dev Lock single token so they can't be transferred from the contract.
* Once locked it can't be unlocked
*/
function lockToken(address token) public onlyOwner {
_lockToken(token);
}
/**
* @dev Lock multiple tokens so they can't be transferred from the contract.
* Once locked it can't be unlocked
*/
function lockTokens(address[] memory tokens) public onlyOwner {
_lockTokens(tokens);
}
/**
* @dev Lock single token so they can't be transferred from the contract.
* Once locked it can't be unlocked
*/
function _lockToken(address token) internal {
lockedTokens[token] = true;
}
/**
* @dev Lock multiple tokens so they can't be transferred from the contract.
* Once locked it can't be unlocked
*/
function _lockTokens(address[] memory tokens) internal {
for (uint256 i = 0; i < tokens.length; i++) {
_lockToken(tokens[i]);
}
}
}
| contract SweeperUpgradeable is OwnableUpgradeable {
struct NFT {
IERC721 nftaddress;
uint256[] ids;
}
mapping(address => bool) public lockedTokens;
bool public allowNativeSweep;
event SweepWithdrawToken(
address indexed receiver,
IERC20 indexed token,
uint256 balance
);
event SweepWithdrawNFTs(address indexed receiver, NFT[] indexed nfts);
event SweepWithdrawNative(address indexed receiver, uint256 balance);
/**
* @dev Transfers erc20 tokens to owner
* Only owner of contract can call this function
*/
function sweepTokens(IERC20[] memory tokens, address to) public onlyOwner {
NFT[] memory empty;
sweepTokensAndNFTs(tokens, empty, to);
}
/**
* @dev Transfers NFT to owner
* Only owner of contract can call this function
*/
function sweepNFTs(NFT[] memory nfts, address to) public onlyOwner {
IERC20[] memory empty;
sweepTokensAndNFTs(empty, nfts, to);
}
/**
* @dev Transfers ERC20 and NFT to owner
* Only owner of contract can call this function
*/
function sweepTokensAndNFTs(
IERC20[] memory tokens,
NFT[] memory nfts,
address to
) public onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
IERC20 token = tokens[i];
require(!lockedTokens[address(token)], "Tokens can't be swept");
uint256 balance = token.balanceOf(address(this));
token.transfer(to, balance);
emit SweepWithdrawToken(to, token, balance);
}
for (uint256 i = 0; i < nfts.length; i++) {
IERC721 nftaddress = nfts[i].nftaddress;
require(
!lockedTokens[address(nftaddress)],
"Tokens can't be swept"
);
uint256[] memory ids = nfts[i].ids;
for (uint256 j = 0; j < ids.length; j++) {
nftaddress.safeTransferFrom(address(this), to, ids[j]);
}
}
emit SweepWithdrawNFTs(to, nfts);
}
/// @notice Sweep native coin
/// @param _to address the native coins should be transferred to
function sweepNative(address payable _to) public onlyOwner {
require(allowNativeSweep, "Not allowed");
uint256 balance = address(this).balance;
_to.transfer(balance);
emit SweepWithdrawNative(_to, balance);
}
/**
* @dev Refuse native sweep.
* Once refused can't be allowed again
*/
function refuseNativeSweep() public onlyOwner {
allowNativeSweep = false;
}
/**
* @dev Lock single token so they can't be transferred from the contract.
* Once locked it can't be unlocked
*/
function lockToken(address token) public onlyOwner {
_lockToken(token);
}
/**
* @dev Lock multiple tokens so they can't be transferred from the contract.
* Once locked it can't be unlocked
*/
function lockTokens(address[] memory tokens) public onlyOwner {
_lockTokens(tokens);
}
/**
* @dev Lock single token so they can't be transferred from the contract.
* Once locked it can't be unlocked
*/
function _lockToken(address token) internal {
lockedTokens[token] = true;
}
/**
* @dev Lock multiple tokens so they can't be transferred from the contract.
* Once locked it can't be unlocked
*/
function _lockTokens(address[] memory tokens) internal {
for (uint256 i = 0; i < tokens.length; i++) {
_lockToken(tokens[i]);
}
}
}
| 27,633 |
200 | // our simple algo get the lowest apr strat cycle through and see who could take its funds plus want for the highest apr | _lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
| _lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
| 30,658 |
4 | // Interactions | uint256 tokensToTransfer = (theFraction*totalAssets())/ONE_IN_TEN_DECIMALS;
IERC20(STAKING_TOKEN).safeTransfer(msg.sender, tokensToTransfer);
emit FeesTaken(entitledFeesInDollars, averagePoolBalanceInDollars, tokensToTransfer);
| uint256 tokensToTransfer = (theFraction*totalAssets())/ONE_IN_TEN_DECIMALS;
IERC20(STAKING_TOKEN).safeTransfer(msg.sender, tokensToTransfer);
emit FeesTaken(entitledFeesInDollars, averagePoolBalanceInDollars, tokensToTransfer);
| 4,840 |
36 | // Returns the downcasted int8 from int256, reverting onoverflow (when the input is less than smallest int8 orgreater than largest int8). Counterpart to Solidity's `int8` operator. Requirements: - input must fit into 8 bits. _Available since v3.1._ / | function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
| function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
| 4,315 |
11 | // MAINNET ADDRESSES The contracts in this list should correspond to MCD core contracts, verify against the current release list at: https:changelog.makerdao.com/releases/mainnet/1.0.9/contracts.json |
address constant mcd_vat35 = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; //inject NONSTANDARD NAMING
address constant mcd_jug497 = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; //inject NONSTANDARD NAMING
address constant mcd_vow892 = 0xA950524441892A31ebddF91d3cEEFa04Bf454466; //inject NONSTANDARD NAMING
address constant ilk_registry964 = 0xbE4F921cdFEf2cF5080F9Cf00CC2c14F1F96Bd07; //inject NONSTANDARD NAMING
uint256 constant million677 = 10 ** 6; //inject NONSTANDARD NAMING
uint256 constant rad54 = 10 ** 45; //inject NONSTANDARD NAMING
|
address constant mcd_vat35 = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; //inject NONSTANDARD NAMING
address constant mcd_jug497 = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; //inject NONSTANDARD NAMING
address constant mcd_vow892 = 0xA950524441892A31ebddF91d3cEEFa04Bf454466; //inject NONSTANDARD NAMING
address constant ilk_registry964 = 0xbE4F921cdFEf2cF5080F9Cf00CC2c14F1F96Bd07; //inject NONSTANDARD NAMING
uint256 constant million677 = 10 ** 6; //inject NONSTANDARD NAMING
uint256 constant rad54 = 10 ** 45; //inject NONSTANDARD NAMING
| 45,602 |
0 | // Mapping from bundle UID => bundle info. | mapping(uint256 => BundleInfo) private bundle;
| mapping(uint256 => BundleInfo) private bundle;
| 15,557 |
81 | // 设置众筹结束时间 | function setClosingTime(uint256 _closingTime) onlyOwner public {
require(_closingTime >= block.timestamp);
require(_closingTime >= openingTime);
closingTime = _closingTime;
}
| function setClosingTime(uint256 _closingTime) onlyOwner public {
require(_closingTime >= block.timestamp);
require(_closingTime >= openingTime);
closingTime = _closingTime;
}
| 28,598 |
154 | // wearable energy | uint256 wearableEnergy;
| uint256 wearableEnergy;
| 41,796 |
6 | // constructor for the StakingTokenWrapper/_tribalChief the TribalChief contract/_beneficiary the recipient of all harvested TRIBE | constructor(
ITribalChief _tribalChief,
address _beneficiary
| constructor(
ITribalChief _tribalChief,
address _beneficiary
| 52,413 |
130 | // 10% given to the governance treasury | fryToken.mint(address(governanceTreasury), uint(10000000).mul(10 ** uint256(fryToken.decimals())));
| fryToken.mint(address(governanceTreasury), uint(10000000).mul(10 ** uint256(fryToken.decimals())));
| 31,512 |
265 | // Records the owner of a given tokenId / | function _recordOwner(
address _keyOwner,
uint _tokenId
) internal
| function _recordOwner(
address _keyOwner,
uint _tokenId
) internal
| 41,612 |
39 | // The ordered list of calldata to be passed to each call | bytes[] calldatas;
| bytes[] calldatas;
| 4,602 |
3 | // Constructor / | constructor() {
FARM_BOOSTER_PROXY_FACTORY = msg.sender;
}
| constructor() {
FARM_BOOSTER_PROXY_FACTORY = msg.sender;
}
| 32,886 |
61 | // Admin - Add a rewards programme | function addRewardsProgramme(uint256 _allocPoint, uint256 _minStakingLengthInBlocks, bool _withUpdate) external {
require(
accessControls.hasAdminRole(_msgSender()),
// StakingRewards.addRewardsProgramme: Only admin
"OA"
);
require(
isActiveRewardProgramme[_minStakingLengthInBlocks] == false,
// StakingRewards.addRewardsProgramme: Programme is already active
"PAA"
);
// StakingRewards.addRewardsProgramme: Invalid alloc point
require(_allocPoint > 0, "IAP");
if (_withUpdate) {
massUpdateRewardProgrammes();
}
uint256 lastRewardBlock = _getBlock() > startBlock ? _getBlock() : startBlock;
rewardProgrammes.push(
RewardProgramme({
minStakingLengthInBlocks: _minStakingLengthInBlocks,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accTokensPerShare: 0,
totalStaked: 0
})
);
isActiveRewardProgramme[_minStakingLengthInBlocks] = true;
emit RewardProgrammeAdded(_allocPoint, _minStakingLengthInBlocks);
}
| function addRewardsProgramme(uint256 _allocPoint, uint256 _minStakingLengthInBlocks, bool _withUpdate) external {
require(
accessControls.hasAdminRole(_msgSender()),
// StakingRewards.addRewardsProgramme: Only admin
"OA"
);
require(
isActiveRewardProgramme[_minStakingLengthInBlocks] == false,
// StakingRewards.addRewardsProgramme: Programme is already active
"PAA"
);
// StakingRewards.addRewardsProgramme: Invalid alloc point
require(_allocPoint > 0, "IAP");
if (_withUpdate) {
massUpdateRewardProgrammes();
}
uint256 lastRewardBlock = _getBlock() > startBlock ? _getBlock() : startBlock;
rewardProgrammes.push(
RewardProgramme({
minStakingLengthInBlocks: _minStakingLengthInBlocks,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accTokensPerShare: 0,
totalStaked: 0
})
);
isActiveRewardProgramme[_minStakingLengthInBlocks] = true;
emit RewardProgrammeAdded(_allocPoint, _minStakingLengthInBlocks);
}
| 26,567 |
115 | // encode a uint112 as a UQ112x112 | function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
| function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
| 9,873 |
49 | // The total transfer amount is the same as the deducted amount | require(totalTransfer == deductedAmount, "panic, calculation error");
| require(totalTransfer == deductedAmount, "panic, calculation error");
| 31,243 |
594 | // Public Mint Monai Universe/ | function mintMonai(uint256 numberOfTokens)
external
payable
| function mintMonai(uint256 numberOfTokens)
external
payable
| 58,276 |
281 | // show founder caps | function getfoundercaps() external view returns (uint16,uint8,uint8) {
return(founderpackcap1,founderpackcap2,founderpackcap3);
}
| function getfoundercaps() external view returns (uint16,uint8,uint8) {
return(founderpackcap1,founderpackcap2,founderpackcap3);
}
| 18,884 |
19 | // Allows the owner to update dynamic L2OutputOracle config._l2OutputOracleDynamicConfig Dynamic L2OutputOracle config. / | function updateL2OutputOracleDynamicConfig(
L2OutputOracleDynamicConfig memory _l2OutputOracleDynamicConfig
| function updateL2OutputOracleDynamicConfig(
L2OutputOracleDynamicConfig memory _l2OutputOracleDynamicConfig
| 14,948 |
519 | // Burns `amount` tokens from `owner`'s balance.//ownerThe address to burn tokens from./amount The amount of tokens to burn.// return If burning the tokens was successful. | function burnFrom(address owner, uint256 amount) external returns (bool);
| function burnFrom(address owner, uint256 amount) external returns (bool);
| 44,461 |
208 | // Verify only the transfer quantity is subtracted | require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
| require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
| 57,555 |
13 | // Check for preico | if (now <= start + ratePreICOEnd) {
rate = ratePreICO;
}
| if (now <= start + ratePreICOEnd) {
rate = ratePreICO;
}
| 11,799 |
0 | // Ethereum addresses of multisig owners | address public owner1;
address public owner2;
| address public owner1;
address public owner2;
| 47,710 |
95 | // fromReturnsBSestimate first calculates the stddev of an array of price returns then uses that as the volatility param for the blackScholesEstimate _numbers uint256[] array of price returns for volatility calculation _underlying uint256 price of the underlying asset _time uint256 days to expiration in years multiplied to remove decimals / | function retBasedBlackScholesEstimate(
uint256[] memory _numbers,
uint256 _underlying,
uint256 _time
| function retBasedBlackScholesEstimate(
uint256[] memory _numbers,
uint256 _underlying,
uint256 _time
| 13,599 |
8 | // ------ SUBSCRIPTION FUNCTIONS ------ /// | function subscribeToChannel(uint256 _channelId) public payable {
require(
msg.value == CHANNEL_SUBSCRIPTION_FEE,
"Must pay exact fee to subscribe"
);
channelIdToUserSubscriptionStatus[currentFeePeriod][_channelId][msg
.sender] = true;
}
| function subscribeToChannel(uint256 _channelId) public payable {
require(
msg.value == CHANNEL_SUBSCRIPTION_FEE,
"Must pay exact fee to subscribe"
);
channelIdToUserSubscriptionStatus[currentFeePeriod][_channelId][msg
.sender] = true;
}
| 28,075 |
0 | // Renaming this contract/ solhint-disable / | contract BondingCurve is BancorFormula {
}
| contract BondingCurve is BancorFormula {
}
| 49,546 |
2 | // 1 token === 1 day |
if (apiKey.startDate == 0) {
|
if (apiKey.startDate == 0) {
| 25,453 |
52 | // fallback payable function to receive ether from other contract addresses | fallback() external payable {}
}
| fallback() external payable {}
}
| 30,529 |
46 | // Places bid for canvas that is in the state STATE_INITIAL_BIDDING. If somebody is outbid his pending withdrawals will be to topped up./ | function makeBid(uint32 _canvasId) external payable stateBidding(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
Bid storage oldBid = bids[_canvasId];
if (msg.value < minimumBidAmount || msg.value <= oldBid.amount) {
revert();
}
if (oldBid.bidder != 0x0 && oldBid.amount > 0) {
//return old bidder his money
addPendingWithdrawal(oldBid.bidder, oldBid.amount);
}
uint finishTime = canvas.initialBiddingFinishTime;
if (finishTime == 0) {
canvas.initialBiddingFinishTime = getTime() + BIDDING_DURATION;
}
bids[_canvasId] = Bid(msg.sender, msg.value);
if (canvas.owner != 0x0) {
addressToCount[canvas.owner]--;
}
canvas.owner = msg.sender;
addressToCount[msg.sender]++;
emit BidPosted(_canvasId, msg.sender, msg.value, canvas.initialBiddingFinishTime);
}
| function makeBid(uint32 _canvasId) external payable stateBidding(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
Bid storage oldBid = bids[_canvasId];
if (msg.value < minimumBidAmount || msg.value <= oldBid.amount) {
revert();
}
if (oldBid.bidder != 0x0 && oldBid.amount > 0) {
//return old bidder his money
addPendingWithdrawal(oldBid.bidder, oldBid.amount);
}
uint finishTime = canvas.initialBiddingFinishTime;
if (finishTime == 0) {
canvas.initialBiddingFinishTime = getTime() + BIDDING_DURATION;
}
bids[_canvasId] = Bid(msg.sender, msg.value);
if (canvas.owner != 0x0) {
addressToCount[canvas.owner]--;
}
canvas.owner = msg.sender;
addressToCount[msg.sender]++;
emit BidPosted(_canvasId, msg.sender, msg.value, canvas.initialBiddingFinishTime);
}
| 4,630 |
14 | // Sets the cost for deploying pools _deploymentCost: Amount of BNB to pay / | function setDeploymentCost(uint256 _deploymentCost) external onlyOwner {
require(deploymentCost != _deploymentCost, "Already set");
deploymentCost = _deploymentCost;
emit NewDeploymentCost(_deploymentCost);
}
| function setDeploymentCost(uint256 _deploymentCost) external onlyOwner {
require(deploymentCost != _deploymentCost, "Already set");
deploymentCost = _deploymentCost;
emit NewDeploymentCost(_deploymentCost);
}
| 27,114 |
142 | // withdraw nfts from farm/only can call by nfts's owner, also claim reward earned/burn an amount of farmingToken (if needed) from msg.sender/fId farm's id/nftIds nfts to withdraw | function withdraw(uint256 fId, uint256[] memory nftIds) external;
| function withdraw(uint256 fId, uint256[] memory nftIds) external;
| 19,062 |
15 | // 私募和ICO解锁时间 2018-01-15 00:00:00 | uint public unlockTime = 1515945600;
| uint public unlockTime = 1515945600;
| 4,812 |
101 | // CityToken with Governance. | contract DelhiCityToken is ERC20("DELHI.cityswap.io", "DELHI"), Ownable {
uint256 public constant MAX_SUPPLY = 21285000 * 10**18;
/**
* @notice Creates `_amount` token to `_to`. Must only be called by the owner (TravelAgency).
*/
function mint(address _to, uint256 _amount) public onlyOwner {
uint256 _totalSupply = totalSupply();
if(_totalSupply.add(_amount) > MAX_SUPPLY) {
_amount = MAX_SUPPLY.sub(_totalSupply);
}
require(_totalSupply.add(_amount) <= MAX_SUPPLY);
_mint(_to, _amount);
}
}
| contract DelhiCityToken is ERC20("DELHI.cityswap.io", "DELHI"), Ownable {
uint256 public constant MAX_SUPPLY = 21285000 * 10**18;
/**
* @notice Creates `_amount` token to `_to`. Must only be called by the owner (TravelAgency).
*/
function mint(address _to, uint256 _amount) public onlyOwner {
uint256 _totalSupply = totalSupply();
if(_totalSupply.add(_amount) > MAX_SUPPLY) {
_amount = MAX_SUPPLY.sub(_totalSupply);
}
require(_totalSupply.add(_amount) <= MAX_SUPPLY);
_mint(_to, _amount);
}
}
| 36,573 |
145 | // Burns the specified value from the sender's balance. Sender's balanced is subtracted by the amount they wish to burn. _valueThe amount to burn. return success true if the burn succeeded./ | function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true, "account blocked");
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender, "disallow burning more, than amount of the balance");
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
| function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true, "account blocked");
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender, "disallow burning more, than amount of the balance");
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
| 38,271 |
61 | // Get position information | function getPosition(uint id) external override view returns (Position memory) {
return positionMap[id];
}
| function getPosition(uint id) external override view returns (Position memory) {
return positionMap[id];
}
| 61,818 |
5 | // Special Mint | uint256 public specialEthPrice;
uint256 public specialTokenPrice;
address public specialToken;
uint256 public transferPrice = 0.05 ether;
uint256 public refFee = 10; //10%
SharedData public sharedData;
bool public claimEnable = false;
| uint256 public specialEthPrice;
uint256 public specialTokenPrice;
address public specialToken;
uint256 public transferPrice = 0.05 ether;
uint256 public refFee = 10; //10%
SharedData public sharedData;
bool public claimEnable = false;
| 32,647 |
28 | // transfers token considering approvals / | function _approveTransfer(
address spender,
address from,
address to,
uint256 tokenId
| function _approveTransfer(
address spender,
address from,
address to,
uint256 tokenId
| 6,953 |
84 | // Calc base ticks depending on base threshold and tickspacing | function baseTicks(int24 currentTick, int24 baseThreshold, int24 tickSpacing) internal pure returns(int24 tickLower, int24 tickUpper) {
int24 tickFloor = floor(currentTick, tickSpacing);
tickLower = tickFloor - baseThreshold;
tickUpper = tickFloor + baseThreshold;
}
| function baseTicks(int24 currentTick, int24 baseThreshold, int24 tickSpacing) internal pure returns(int24 tickLower, int24 tickUpper) {
int24 tickFloor = floor(currentTick, tickSpacing);
tickLower = tickFloor - baseThreshold;
tickUpper = tickFloor + baseThreshold;
}
| 4,146 |
9 | // Payment is in BEP-20 | uint256 cost = getCost(paymentToken, numberOfTokens);
require(
paymentToken.allowance(msg.sender, address(this)) >= cost / 1000000000000,
"Not enough allowance"
);
_buyTokens(numberOfTokens, referrer);
paymentToken.safeTransferFrom(msg.sender, treasury, cost / 1000000000000);
| uint256 cost = getCost(paymentToken, numberOfTokens);
require(
paymentToken.allowance(msg.sender, address(this)) >= cost / 1000000000000,
"Not enough allowance"
);
_buyTokens(numberOfTokens, referrer);
paymentToken.safeTransferFrom(msg.sender, treasury, cost / 1000000000000);
| 2,553 |
30 | // The external account linked to the HashflowPool on the source chain.If the HashflowPool holds funds, this should be address(0). / | address srcExternalAccount;
| address srcExternalAccount;
| 10,359 |
18 | // Mapping from 'Largest tokenId of a batch of tokens with the same baseURI'to base URI for the respective batch of tokens. //Mapping from 'Largest tokenId of a batch of 'delayed-reveal' tokens withthe same baseURI' to encrypted base URI for the respective batch of tokens. //Mapping from address => total number of NFTs a wallet has claimed. | mapping(address => uint256) public walletClaimCount;
| mapping(address => uint256) public walletClaimCount;
| 29,090 |
294 | // CHANGE PARAMETERS / | function setInit(address _witchesanddemons, address _newt) external onlyOwner{
witchesanddemons = WitchesandDemons(_witchesanddemons); // reference to the WitchesandDemons NFT contract
newt = ITNewt(_newt); //reference to the $NEWT token
}
| function setInit(address _witchesanddemons, address _newt) external onlyOwner{
witchesanddemons = WitchesandDemons(_witchesanddemons); // reference to the WitchesandDemons NFT contract
newt = ITNewt(_newt); //reference to the $NEWT token
}
| 19,744 |
201 | // forward funds to the wallet | forwardFunds(purchaser, purchaseAmount);
| forwardFunds(purchaser, purchaseAmount);
| 79,889 |
28 | // transfer bmi profit to the user | bmiToken.transfer(_msgSender(), profit);
emit StakingBMIProfitWithdrawn(tokenId, policyBookAddress, _msgSender(), profit);
| bmiToken.transfer(_msgSender(), profit);
emit StakingBMIProfitWithdrawn(tokenId, policyBookAddress, _msgSender(), profit);
| 40,823 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.