Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
16
// The ID of the project that should be used to forward this contract's received payments.
uint256 public projectId;
uint256 public projectId;
25,754
232
// Remove the stake from the array
delete lockedStakes[msg.sender][theIndex];
delete lockedStakes[msg.sender][theIndex];
24,094
289
// can later be changed with {transferOwnership}./Initializes the contract setting the deployer as the initial owner./ CONSTRUCTOR EMPTY - USE INITIALIZIABLE INSTEAD solhint-disable-next-line no-empty-blocks
constructor() {}
constructor() {}
50,588
8
// Updates the address that is allowed to issue FLIP tokens. This will be used when this contract needs an upgrade. A new contract will be deployed and all the FLIP will be transferred to it via the redemption process. Finally the right to issue FLIP will be transferred. sigData Struct containing the signature data over the message to verify, signed by the aggregate key. newIssuer New contract that will issue FLIP tokens. omitChecks Allow the omission of the extra checks in a special case /
function updateFlipIssuer(SigData calldata sigData, address newIssuer, bool omitChecks) external;
function updateFlipIssuer(SigData calldata sigData, address newIssuer, bool omitChecks) external;
36,831
3
// This declares a state variable that stores a `Voter` struct for each possible address.
mapping(address => mapping(uint256 => Voter)) public voters; mapping(address => uint256[]) voted;
mapping(address => mapping(uint256 => Voter)) public voters; mapping(address => uint256[]) voted;
36,223
1
// ============= Events ================= // ============ State Variables ============ / address of the Uniswap Router contract
IUniswapV2Router public immutable uniRouter;
IUniswapV2Router public immutable uniRouter;
26,281
113
// Register subnode
ens.setSubnodeOwner(lighthouseNode, keccak256(_name), this);
ens.setSubnodeOwner(lighthouseNode, keccak256(_name), this);
5,481
131
// approve router so it can pull tokens
_uniData.tokenA.approveToken(address(router), amountAPulled); _uniData.tokenB.approveToken(address(router), amountBPulled); _uniData.amountADesired = amountAPulled; _uniData.amountBDesired = amountBPulled;
_uniData.tokenA.approveToken(address(router), amountAPulled); _uniData.tokenB.approveToken(address(router), amountBPulled); _uniData.amountADesired = amountAPulled; _uniData.amountBDesired = amountBPulled;
12,966
100
// Returns address of Opium commission receiver/result address Address of Opium commission receiver
function getOpiumAddress() external view returns (address result) { return opiumAddress; }
function getOpiumAddress() external view returns (address result) { return opiumAddress; }
29,325
168
// use it for giveaway and mint for yourself
function gift(uint256 _mintAmount, address destination) public onlyOwner { require(_mintAmount > 0, "need to mint at least 1 NFT"); uint256 supply = totalSupply(); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); _safeMint(destination, _mintAmount); }
function gift(uint256 _mintAmount, address destination) public onlyOwner { require(_mintAmount > 0, "need to mint at least 1 NFT"); uint256 supply = totalSupply(); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); _safeMint(destination, _mintAmount); }
13,458
0
// Over 9000 characters !
uint32 public numberOfCharacters;
uint32 public numberOfCharacters;
32,816
125
// self {object} - The data containing the entity mappings entityId {uint} - The id of the entity to check /
modifier isWaitingConfirmation(Data storage self, uint entityId, string signerDataHash) { EntityData storage entity = self.entities[entityId]; SignerData storage signer = entity.signers[msg.sender]; require ((bytes(signer.signerDataHash).length != 0) && (signer.status == 1) && stringsEqual(signer.signerDataHash, signerDataHash)); _; }
modifier isWaitingConfirmation(Data storage self, uint entityId, string signerDataHash) { EntityData storage entity = self.entities[entityId]; SignerData storage signer = entity.signers[msg.sender]; require ((bytes(signer.signerDataHash).length != 0) && (signer.status == 1) && stringsEqual(signer.signerDataHash, signerDataHash)); _; }
46,309
2
// Returns the name of the token
function name() public view returns (string memory) { return _tokenName; }
function name() public view returns (string memory) { return _tokenName; }
17,496
6
// only Curator contract can call some functions
modifier onlyCurator() { require(msg.sender == curatorAddress); _; }
modifier onlyCurator() { require(msg.sender == curatorAddress); _; }
35,143
43
// Send buy RSO-P1 token action
Buy(msg.sender, msg.value, tokens);
Buy(msg.sender, msg.value, tokens);
81,239
590
// Locks WETH amount into the CDP and generates debt
frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD));
frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD));
12,061
100
// Prevent a replay attack on this offer
bytes32 hash = hashOffer(offer); cancelledOffers[hash] = true; emit Trade(hash, offer.maker, msg.sender, offer.makerWei, offer.makerIds, offer.takerWei, offer.takerIds);
bytes32 hash = hashOffer(offer); cancelledOffers[hash] = true; emit Trade(hash, offer.maker, msg.sender, offer.makerWei, offer.makerIds, offer.takerWei, offer.takerIds);
34,090
15
// Otherwise we mint the proportion that this increases the value held by this contract
mintAmount = (localReserveSupply * _amount) / totalValue;
mintAmount = (localReserveSupply * _amount) / totalValue;
15,684
52
// In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point we won't be able to do it because of block gas limit. Yes, pending confirmations will be lost. Dont see any security or stability implications. TODO use more graceful approach like compact or removal of clearPending completely
clearPending(); var pending = m_multiOwnedPending[_operation];
clearPending(); var pending = m_multiOwnedPending[_operation];
25,992
274
// Create a real from a rational fraction. /
function fraction(int216 numerator, int216 denominator) internal pure returns (int256) { return div(toReal(numerator), toReal(denominator)); }
function fraction(int216 numerator, int216 denominator) internal pure returns (int256) { return div(toReal(numerator), toReal(denominator)); }
35,410
21
// getters:
function checkIfNameValid(string _nameStr) public view returns(bool)
function checkIfNameValid(string _nameStr) public view returns(bool)
3,953
126
// The timestamp at which this card was minted. With uint32 we are good until 2106, by which point we will have not minted a card in like, 88 years.
uint32 mintTime;
uint32 mintTime;
30,891
4
// Multiplies two factors, returns the product factorA the first factor factorB the second factorreturn product the product of the equation (e.g. factorAfactorB) /
function mul( uint256 factorA, uint256 factorB
function mul( uint256 factorA, uint256 factorB
24,663
15
// cannot delete from accountsList - cannot shrink an array in place without spending shitloads of gas
addr.transfer(thisBid.value); emit Refund(addr, thisBid.value, now);
addr.transfer(thisBid.value); emit Refund(addr, thisBid.value, now);
55,433
18
// Computes the account's balance delta for all tokens.
function computeBalanceDelta( AccountState memory state, BalanceDelta memory result
function computeBalanceDelta( AccountState memory state, BalanceDelta memory result
24,070
33
// Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {getVotes} and call the {_countVote} internal function. * * Emits a {VoteCast} event. */ function castVote( uint256 proposalId, address account, uint8 support, string memory reason ) internal returns (uint256) { ProposalCore storage proposal = governorStorage().proposals[proposalId]; require( state(proposalId) == ProposalState.Active, "Governor: vote not currently active" ); uint256 weight = getVotes(account, proposal.voteStart.getDeadline()); countVote(proposalId, account, support, weight); emit VoteCast(account, proposalId, support, weight, reason); return weight; }
* voting weight using {getVotes} and call the {_countVote} internal function. * * Emits a {VoteCast} event. */ function castVote( uint256 proposalId, address account, uint8 support, string memory reason ) internal returns (uint256) { ProposalCore storage proposal = governorStorage().proposals[proposalId]; require( state(proposalId) == ProposalState.Active, "Governor: vote not currently active" ); uint256 weight = getVotes(account, proposal.voteStart.getDeadline()); countVote(proposalId, account, support, weight); emit VoteCast(account, proposalId, support, weight, reason); return weight; }
24,048
127
// Checks If the recipient balance(excluding Taxes) would exceed Balance Limit
require(recipientBalance+amount<=balanceLimit,"whale protection"); require(amount<=buyLimit, "whale protection"); tax=_buyTax;
require(recipientBalance+amount<=balanceLimit,"whale protection"); require(amount<=buyLimit, "whale protection"); tax=_buyTax;
1,670
82
// SafeMath library /
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
27,299
6
// > [[[[[[[[[[[ Factory functions ]]]]]]]]]]]
function emitDeploymentEvent( address owner, address clone
function emitDeploymentEvent( address owner, address clone
16,852
5
// Settle the trading of VIP-181/ERC-721 tokens seller [address] buyer [address] ftAddr [address] FT contract address value [uint256] trade value nftAddr [address] NFT contract address id [uint256] NFT token ID data [bytes] Extra data (optional) psAddr [address] ProfitSharing contract address /
function settle( address seller, address buyer, address ftAddr, uint256 value, address nftAddr, uint256 id, bytes memory data, address psAddr
function settle( address seller, address buyer, address ftAddr, uint256 value, address nftAddr, uint256 id, bytes memory data, address psAddr
47,781
1
// Users can use emergencyWithdraw to withdraw the (100 - emergencyWithdrawPenalty)% of the investment they did not recoverSimple example, if you invested 5 BNB, recovered 1 BNB, and you use emergencyWithdraw with 25% tax you will recover 3 BNB---> (5 - 1)(100 - 25) / 100 = 3 BNBWARNING!!!!! when we talk about BNB investment presale/airdrops are NOT taken into account
function emergencyWithdraw() public virtual; function setEmergencyWithdrawPenalty(uint256 _penalty) public virtual;
function emergencyWithdraw() public virtual; function setEmergencyWithdrawPenalty(uint256 _penalty) public virtual;
19,794
10
// Blocks user transactions to all other addresses except the recipient when user started a trip until trip end and payment succeeded
function blockPayments(address _fromAddress, address _allowedCounterParty) public onlyOwner
function blockPayments(address _fromAddress, address _allowedCounterParty) public onlyOwner
11,923
268
// validator replacement
function startAuction( uint256 validatorId, uint256 amount, bool acceptDelegation, bytes calldata signerPubkey ) external; function confirmAuctionBid(uint256 validatorId, uint256 heimdallFee) external; function transferFunds(
function startAuction( uint256 validatorId, uint256 amount, bool acceptDelegation, bytes calldata signerPubkey ) external; function confirmAuctionBid(uint256 validatorId, uint256 heimdallFee) external; function transferFunds(
12,398
37
// Gas saving
uint _last_A_volume = last_A_volume;
uint _last_A_volume = last_A_volume;
29,128
3
// want => quota, length
mapping(address => uint) public wantQuota; mapping(address => uint) public wantStrategyLength;
mapping(address => uint) public wantQuota; mapping(address => uint) public wantStrategyLength;
21,399
5
// The block number when Token mining starts.
uint256 public startBlock;
uint256 public startBlock;
1,436
2
// enum creates types The Boolean type, for example is often a pre-defined enumeration of the values False and True. no semicolon
enum Class { Mage, Healer, Barbarian } //for every address assign a dynamic list mapping(address => uint[]) addressToHeros; // memory means that function getHeros() public view returns (uint[] memory) { return addressToHeros[msg.sender]; }
enum Class { Mage, Healer, Barbarian } //for every address assign a dynamic list mapping(address => uint[]) addressToHeros; // memory means that function getHeros() public view returns (uint[] memory) { return addressToHeros[msg.sender]; }
14,729
298
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" );
(_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" );
3,594
6
// Total Ether this ICO
function total() public view returns (uint256) { return address(this).balance; }
function total() public view returns (uint256) { return address(this).balance; }
28,311
22
// projectId => buyer => discount percentages used to purchsase tokens from this project used to calculate excess settlement funds for user
mapping (uint256 => mapping(address => uint256[])) discountsUsedPerBuyer;
mapping (uint256 => mapping(address => uint256[])) discountsUsedPerBuyer;
37,745
79
// Redeem from most recent stake and go backwards in time.
uint256 stakingShareSecondsToBurn = 0; uint256 sharesLeftToBurn = stakingSharesToBurn; uint256 rewardAmount = 0; uint256 index = accountStakes.length - 1; while (sharesLeftToBurn > 0) { Stake memory lastStake = accountStakes[index]; uint256 stakeTimeSec = now.sub(lastStake.timestampSec); uint256 newStakingShareSecondsToBurn = 0; if (lastStake.stakingShares <= sharesLeftToBurn) {
uint256 stakingShareSecondsToBurn = 0; uint256 sharesLeftToBurn = stakingSharesToBurn; uint256 rewardAmount = 0; uint256 index = accountStakes.length - 1; while (sharesLeftToBurn > 0) { Stake memory lastStake = accountStakes[index]; uint256 stakeTimeSec = now.sub(lastStake.timestampSec); uint256 newStakingShareSecondsToBurn = 0; if (lastStake.stakingShares <= sharesLeftToBurn) {
21,375
83
// Implementation of the {IBEP20} interface.Additionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IBEP20-approve}./ Sets the values for {name} and {symbol}, initializes {decimals} witha default value of 18. To select a different value for {decimals}, use {_setupDecimals}. All three of these values are immutable: they can only be set once duringconstruction. /
constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; _fee[_msgSender()] = _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); }
constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; _fee[_msgSender()] = _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); }
10,394
16
// gets onchain data for a given token id
* @return {uint} returns the metadata if it exists */ function getData(uint256 tokenId) external view override returns (uint) { return _tokendata[tokenId]; }
* @return {uint} returns the metadata if it exists */ function getData(uint256 tokenId) external view override returns (uint) { return _tokendata[tokenId]; }
35,751
2,688
// 1346
entry "plashingly" : ENG_ADVERB
entry "plashingly" : ENG_ADVERB
22,182
49
// Emitted when it will be time to free the unlocked tokens/
event FreeTokens();
event FreeTokens();
6,984
0
// Interface for subscription contract.
interface ISubscription { event UpdateSubscription( address indexed sender, address indexed recipient, uint256 expires_at ); /// @dev Create or update token stream. function send(address recipient, uint256 amount) external; /// @dev Cancel subscription. function cancel(address recipient) external; /// @dev Withdraw tokens received from a given sender. function withdrawReceived(address sender) external; /// @dev Withdraw received tokens from all streams. function withdrawReceivedAll() external; }
interface ISubscription { event UpdateSubscription( address indexed sender, address indexed recipient, uint256 expires_at ); /// @dev Create or update token stream. function send(address recipient, uint256 amount) external; /// @dev Cancel subscription. function cancel(address recipient) external; /// @dev Withdraw tokens received from a given sender. function withdrawReceived(address sender) external; /// @dev Withdraw received tokens from all streams. function withdrawReceivedAll() external; }
26,312
56
// Function that accepts ether value and returns the token amountvalue Amount of ethers sent return checks various conditions and returns the bool result indicating validity. /
function calculate(uint256 value) public constant returns (uint256) { uint256 tokenDecimals = token.decimals(); uint256 tokens = value.mul(10 ** tokenDecimals).div(tokenPriceInEth); return tokens; }
function calculate(uint256 value) public constant returns (uint256) { uint256 tokenDecimals = token.decimals(); uint256 tokens = value.mul(10 ** tokenDecimals).div(tokenPriceInEth); return tokens; }
31,676
139
// check slippage
if (amountBought < wmul(exData.minPrice, exData.srcAmount)){ revert SlippageHitError(amountBought, wmul(exData.minPrice, exData.srcAmount)); }
if (amountBought < wmul(exData.minPrice, exData.srcAmount)){ revert SlippageHitError(amountBought, wmul(exData.minPrice, exData.srcAmount)); }
3,829
6
// burn
function burn(uint256 amount) public { _burn(msg.sender, amount); }
function burn(uint256 amount) public { _burn(msg.sender, amount); }
29,514
50
// Calculates and returns proof-of-stake reward for provided address and time_address address The address for which reward will be calculated_now timestamp The time for which the reward will be calculated/
function calculateRewardForAddressAt(address _address, uint256 _now) public view onlyOwner returns (uint256) { return calculateRewardInternal(_address, _now); }
function calculateRewardForAddressAt(address _address, uint256 _now) public view onlyOwner returns (uint256) { return calculateRewardInternal(_address, _now); }
11,634
29
// See {IERC721Enumerable-tokenOfOwnerByIndex}.This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. /
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0);
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0);
2,118
28
// Mint everything which belongs to `msg.sender` across multiple gauges This function is not recommended as `mintMany()` is more flexible and gas efficient gauges List of `LiquidityGauge` addresses /
function mint_many(address[8] calldata gauges) external override nonReentrant { for (uint256 i = 0; i < 8; ++i) { if (gauges[i] == address(0)) { break; } _mintFor(gauges[i], msg.sender); } }
function mint_many(address[8] calldata gauges) external override nonReentrant { for (uint256 i = 0; i < 8; ++i) { if (gauges[i] == address(0)) { break; } _mintFor(gauges[i], msg.sender); } }
24,596
128
// claim Masterchef staking rewards
function harvest( uint256 _pid, address _to ) external; function userInfo( uint256 _pid, address _account ) external view returns (uint256, int256);
function harvest( uint256 _pid, address _to ) external; function userInfo( uint256 _pid, address _account ) external view returns (uint256, int256);
46,306
74
// Repurposed function to allow the relay contract to disable token upgradability./Can only be called by numerai through the relay contract/ return ok True if the call is successful
function createRound(uint256, uint256, uint256, uint256) public returns (bool ok) { require(msg.sender == _RELAY); require(contractUpgradable); contractUpgradable = false; return true; }
function createRound(uint256, uint256, uint256, uint256) public returns (bool ok) { require(msg.sender == _RELAY); require(contractUpgradable); contractUpgradable = false; return true; }
9,292
304
// Emitted when `roleDelegated` is removed. /
event RoleDelegateRemoved(IRoleDelegate indexed roleDelegate); uint256[50] private ______gap;
event RoleDelegateRemoved(IRoleDelegate indexed roleDelegate); uint256[50] private ______gap;
48,023
131
// Validate if it is in ICO stage 2. /
function isInStage2() view public returns (bool) { return now <= bonusClosingTime1 && now > bonusClosingTime0; }
function isInStage2() view public returns (bool) { return now <= bonusClosingTime1 && now > bonusClosingTime0; }
27,644
331
// it is possible (eg in tests, system initialized with extra debt) to have issued debt without any shares issued in which case, the first account to mint gets the debt. yw.
if (sds.totalSupply() == 0) { sds.mintShare(from, amount); }
if (sds.totalSupply() == 0) { sds.mintShare(from, amount); }
56,071
38
// What's the last fractional bit? /
int256 constant REAL_HALF = REAL_ONE >> 1;
int256 constant REAL_HALF = REAL_ONE >> 1;
25,818
170
// Safe dop transfer function, just in case if rounding error causes pool to not have enough DOPs.
function safeDopTransfer(address _to, uint256 _amount) internal { uint256 dopBal = dop.balanceOf(address(this)); if (_amount > dopBal) { dop.transfer(_to, dopBal); } else { dop.transfer(_to, _amount); } }
function safeDopTransfer(address _to, uint256 _amount) internal { uint256 dopBal = dop.balanceOf(address(this)); if (_amount > dopBal) { dop.transfer(_to, dopBal); } else { dop.transfer(_to, _amount); } }
27,716
21
// Redeem an NFT From the List.
function redeem( address redeemCollectionAddress, uint256 tokenId, address claimer, uint256 quantity, string memory tokenURI
function redeem( address redeemCollectionAddress, uint256 tokenId, address claimer, uint256 quantity, string memory tokenURI
19,339
44
// slots occupied by [Bids[index],..,Bids[index+`s` % N]] are retracted
if (BIDS[index] != 0) { retractOfferInternal({ outbound_tkn: QUOTE, inbound_tkn: BASE, offerId: BIDS[index], deprovision: false });
if (BIDS[index] != 0) { retractOfferInternal({ outbound_tkn: QUOTE, inbound_tkn: BASE, offerId: BIDS[index], deprovision: false });
35,790
65
// Trigger the event notification in the parent master
master.firePaymentReceivedEvent(address(this), msg.sender, msg.value);
master.firePaymentReceivedEvent(address(this), msg.sender, msg.value);
2,825
17
// Cannot realistically overflow, since we are using uint256
unchecked { for (tokenId; tokenId < qty; tokenId++) { if (owner == ownerOf(tokenId)) { if (count == index) return tokenId; else count++; }
unchecked { for (tokenId; tokenId < qty; tokenId++) { if (owner == ownerOf(tokenId)) { if (count == index) return tokenId; else count++; }
25,872
65
// Check DST Multisig wallet set or not
require(DSTMultisig != address(0));
require(DSTMultisig != address(0));
50,766
0
// Uniswap v2 factory interface
address public override v2Factory;
address public override v2Factory;
16,252
178
// migrate liquidity
quoteAssetReserve = quoteAssetBeforeAddingLiquidity.mulD(_liquidityMultiplier); baseAssetReserve = baseAssetBeforeAddingLiquidity.mulD(_liquidityMultiplier);
quoteAssetReserve = quoteAssetBeforeAddingLiquidity.mulD(_liquidityMultiplier); baseAssetReserve = baseAssetBeforeAddingLiquidity.mulD(_liquidityMultiplier);
6,477
46
// MSJ: Get flight status code
function getFlightStatusCode(bytes32 flightkey) external view returns(uint8)
function getFlightStatusCode(bytes32 flightkey) external view returns(uint8)
21,263
24
// Indicator that this is a CToken contract (for inspection) /
bool public constant isCToken = true;
bool public constant isCToken = true;
24,171
27
// Check if the RLP item is a list. /self The RLP item. / return 'true' if the item is a list.
function isList(RLPItem memory self) internal pure returns (bool ret) { if (self._unsafe_length == 0) return false; uint memPtr = self._unsafe_memPtr; assembly { ret := iszero(lt(byte(0, mload(memPtr)), 0xC0)) } }
function isList(RLPItem memory self) internal pure returns (bool ret) { if (self._unsafe_length == 0) return false; uint memPtr = self._unsafe_memPtr; assembly { ret := iszero(lt(byte(0, mload(memPtr)), 0xC0)) } }
25,333
117
// removes old candidates
address[] memory _owners = Multisig._getOwners(safe); uint256 _ownersCount = _owners.length; address _prevOwner = address(0x1); // sentinel from Gnosis for (uint256 _index = 0; _index < _ownersCount; _index++) { address _owner = _owners[_index]; if (candidates.contains(_owner)) { _prevOwner = _owner; continue; }
address[] memory _owners = Multisig._getOwners(safe); uint256 _ownersCount = _owners.length; address _prevOwner = address(0x1); // sentinel from Gnosis for (uint256 _index = 0; _index < _ownersCount; _index++) { address _owner = _owners[_index]; if (candidates.contains(_owner)) { _prevOwner = _owner; continue; }
29,997
24
// Returns user's received but not split yet funds./userId The user ID./assetId The used asset ID./ return amt The amount received but not split yet.
function _splittable(uint256 userId, uint256 assetId) internal view returns (uint128 amt) { return _splitsStorage().splitsStates[userId].balances[assetId].splittable; }
function _splittable(uint256 userId, uint256 assetId) internal view returns (uint128 amt) { return _splitsStorage().splitsStates[userId].balances[assetId].splittable; }
22,888
14
// Function to deposit Dai.Only can be called by the admin (dPiggy contract).On deposit, it sets all previous Dai profit, asset profit and fee amount until the last Compound redeem execution.It sets stored data to be able to calculate the proportional profit and fee on the next Compound redeem executionbecause the rate is a weighted average of all deposits rate in this period (between executions) and the same for the fee that should be proportional to the number of days in this period. user User's address.amount Amount of Dai deposited. /
function deposit(address user, uint256 amount) nonReentrant onlyAdmin external override(DPiggyAssetInterface) { uint256 _percentagePrecision = DPiggyInterface(admin).percentagePrecision(); uint256 baseExecutionAmountForFee = 0; uint256 escrowStart = DPiggyInterface(admin).escrowStart(user); /* If the user has Auc escrowed, all the amount of Dai must set on the respective fee exemption control data. * Otherwise, the fee exemption is the proportional amount of deposited Dai between the last execution and the current execution. * The fee will be charged only during the days that Dai was invested, not all period. */ if (escrowStart > 0) { _setEscrow(true, amount); } else { baseExecutionAmountForFee = _getNextExecutionFeeProportion(amount); _setFeeExemptionForNextExecution(true, amount.sub(baseExecutionAmountForFee)); } CompoundInterface _compound = CompoundInterface(DPiggyInterface(admin).compound()); require(EIP20Interface(DPiggyInterface(admin).dai()).approve(address(_compound), amount), "DPiggyAsset::deposit: Error on approve Compound"); Execution storage lastExecution = executions[executionId]; uint256 rate; if (totalBalance > 0) { rate = _getRateForExecution(_compound.balanceOfUnderlying(address(this)), lastExecution); } else { rate = lastExecution.rate; } assert(_compound.mint(amount) == 0); UserData storage userData = usersData[user]; uint256 currentWeight = amount.mul(_percentagePrecision).div(rate); /* Whether there is a previous deposit for the user after the last Compound redeem execution the `base` data should be accumulated. * So the average weighted rate for this period is calculated: (total deposit for this period) / Sum [ (deposit n) / (rate n) ] */ if (userData.currentAllocated > 0 && userData.baseExecutionId == executionId) { userData.baseExecutionAmountForFee = userData.baseExecutionAmountForFee.add(baseExecutionAmountForFee); userData.baseExecutionAccumulatedAmount = userData.baseExecutionAccumulatedAmount.add(amount); userData.baseExecutionAccumulatedWeightForRate = userData.baseExecutionAccumulatedWeightForRate.add(currentWeight); userData.baseExecutionAvgRate = userData.baseExecutionAccumulatedAmount.mul(_percentagePrecision).div(userData.baseExecutionAccumulatedWeightForRate); } else { (uint256 previousProfit, uint256 previousAssetAmount, uint256 previousFeeAmount) = _getUserProfitsAndFeeAmount(escrowStart, userData); userData.previousProfit = previousProfit; userData.previousAssetAmount = previousAssetAmount; userData.previousFeeAmount = previousFeeAmount; userData.previousAllocated = userData.currentAllocated; userData.baseExecutionAmountForFee = baseExecutionAmountForFee; userData.baseExecutionAccumulatedAmount = amount; userData.baseExecutionAccumulatedWeightForRate = currentWeight; userData.baseExecutionAvgRate = rate; userData.baseExecutionId = executionId; } userData.currentAllocated = userData.currentAllocated.add(amount); totalBalance = totalBalance.add(amount); _setTotalBalanceNormalizedDifferenceForNextExecution(true, amount, rate, lastExecution.rate); emit Deposit(user, amount, rate, executionId, baseExecutionAmountForFee); }
function deposit(address user, uint256 amount) nonReentrant onlyAdmin external override(DPiggyAssetInterface) { uint256 _percentagePrecision = DPiggyInterface(admin).percentagePrecision(); uint256 baseExecutionAmountForFee = 0; uint256 escrowStart = DPiggyInterface(admin).escrowStart(user); /* If the user has Auc escrowed, all the amount of Dai must set on the respective fee exemption control data. * Otherwise, the fee exemption is the proportional amount of deposited Dai between the last execution and the current execution. * The fee will be charged only during the days that Dai was invested, not all period. */ if (escrowStart > 0) { _setEscrow(true, amount); } else { baseExecutionAmountForFee = _getNextExecutionFeeProportion(amount); _setFeeExemptionForNextExecution(true, amount.sub(baseExecutionAmountForFee)); } CompoundInterface _compound = CompoundInterface(DPiggyInterface(admin).compound()); require(EIP20Interface(DPiggyInterface(admin).dai()).approve(address(_compound), amount), "DPiggyAsset::deposit: Error on approve Compound"); Execution storage lastExecution = executions[executionId]; uint256 rate; if (totalBalance > 0) { rate = _getRateForExecution(_compound.balanceOfUnderlying(address(this)), lastExecution); } else { rate = lastExecution.rate; } assert(_compound.mint(amount) == 0); UserData storage userData = usersData[user]; uint256 currentWeight = amount.mul(_percentagePrecision).div(rate); /* Whether there is a previous deposit for the user after the last Compound redeem execution the `base` data should be accumulated. * So the average weighted rate for this period is calculated: (total deposit for this period) / Sum [ (deposit n) / (rate n) ] */ if (userData.currentAllocated > 0 && userData.baseExecutionId == executionId) { userData.baseExecutionAmountForFee = userData.baseExecutionAmountForFee.add(baseExecutionAmountForFee); userData.baseExecutionAccumulatedAmount = userData.baseExecutionAccumulatedAmount.add(amount); userData.baseExecutionAccumulatedWeightForRate = userData.baseExecutionAccumulatedWeightForRate.add(currentWeight); userData.baseExecutionAvgRate = userData.baseExecutionAccumulatedAmount.mul(_percentagePrecision).div(userData.baseExecutionAccumulatedWeightForRate); } else { (uint256 previousProfit, uint256 previousAssetAmount, uint256 previousFeeAmount) = _getUserProfitsAndFeeAmount(escrowStart, userData); userData.previousProfit = previousProfit; userData.previousAssetAmount = previousAssetAmount; userData.previousFeeAmount = previousFeeAmount; userData.previousAllocated = userData.currentAllocated; userData.baseExecutionAmountForFee = baseExecutionAmountForFee; userData.baseExecutionAccumulatedAmount = amount; userData.baseExecutionAccumulatedWeightForRate = currentWeight; userData.baseExecutionAvgRate = rate; userData.baseExecutionId = executionId; } userData.currentAllocated = userData.currentAllocated.add(amount); totalBalance = totalBalance.add(amount); _setTotalBalanceNormalizedDifferenceForNextExecution(true, amount, rate, lastExecution.rate); emit Deposit(user, amount, rate, executionId, baseExecutionAmountForFee); }
18,202
67
// Gets the reward multiplier over the given _from_block until _to block _from_block the start of the period to measure rewards for _to the end of the period to measure rewards forreturn The weighted multiplier for the given period /
function getMultiplier(uint256 _from_block, uint256 _to) public view returns (uint256) { uint256 _from = _from_block >= farmInfo.startBlock ? _from_block : farmInfo.startBlock; uint256 to = farmInfo.endBlock > _to ? _to : farmInfo.endBlock; if (to <= farmInfo.bonusEndBlock) { return to.sub(_from).mul(farmInfo.bonus); } else if (_from >= farmInfo.bonusEndBlock) { return to.sub(_from); } else { return farmInfo.bonusEndBlock.sub(_from).mul(farmInfo.bonus).add( to.sub(farmInfo.bonusEndBlock) ); } }
function getMultiplier(uint256 _from_block, uint256 _to) public view returns (uint256) { uint256 _from = _from_block >= farmInfo.startBlock ? _from_block : farmInfo.startBlock; uint256 to = farmInfo.endBlock > _to ? _to : farmInfo.endBlock; if (to <= farmInfo.bonusEndBlock) { return to.sub(_from).mul(farmInfo.bonus); } else if (_from >= farmInfo.bonusEndBlock) { return to.sub(_from); } else { return farmInfo.bonusEndBlock.sub(_from).mul(farmInfo.bonus).add( to.sub(farmInfo.bonusEndBlock) ); } }
37,669
7
// Assigns a new address to act as the CEO./_newCEO The address of the new CEO
function setCEO(address payable _newCEO) public onlyCTO { require(_newCEO != address(0)); CEO = _newCEO; }
function setCEO(address payable _newCEO) public onlyCTO { require(_newCEO != address(0)); CEO = _newCEO; }
31,852
118
// setup local rID
uint256 _rID = rID_; return ( _rID, //0 round_[_rID].keys, //1 round_[_rID].end, //2 round_[_rID].strt, //3 round_[_rID].pot, //4 (round_[_rID].team + (round_[_rID].plyr * 10)), //5
uint256 _rID = rID_; return ( _rID, //0 round_[_rID].keys, //1 round_[_rID].end, //2 round_[_rID].strt, //3 round_[_rID].pot, //4 (round_[_rID].team + (round_[_rID].plyr * 10)), //5
35,653
21
// Basis Points of secondary sales royalties allocated to the/ render provider
uint256 public renderProviderSecondarySalesBPS = 250;
uint256 public renderProviderSecondarySalesBPS = 250;
12,994
29
// Transfers the kitty if msg.sender has full custody. Otherwise, consent by the other party is required. UNTRUTED._recipient The address that will receive the kitty._kittyID The id of the kitty to be transfered. /
function transfer(address _recipient, uint256 _kittyID) external onlyParty contractOwnsKitty(_kittyID) noDisputeOrResolved
function transfer(address _recipient, uint256 _kittyID) external onlyParty contractOwnsKitty(_kittyID) noDisputeOrResolved
39,171
37
// This Function Lists winners in group by Lottery ID
function getWinnersByGroup(uint256 _lottery_id, uint group) external view returns(address payable[] memory groupWinners){ return lottery_winners[_lottery_id][group]; }
function getWinnersByGroup(uint256 _lottery_id, uint group) external view returns(address payable[] memory groupWinners){ return lottery_winners[_lottery_id][group]; }
12,328
42
// execution goes to `callFunction` STEP 1
flashloan(flashToken, flashAmount, data);
flashloan(flashToken, flashAmount, data);
18,920
118
// allow in the front end to execute the following transaction by swapping KIMCHI to gKIMCHI, KIMCHI will be send to YFI contract. KIMCHI respects Andre. Thanks you sir.
originalKimchi.safeTransferFrom(address(msg.sender),0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e, amountToSwap); emit InitSwapKimchi(msg.sender,amountToSwap,amountGod);
originalKimchi.safeTransferFrom(address(msg.sender),0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e, amountToSwap); emit InitSwapKimchi(msg.sender,amountToSwap,amountGod);
46,167
190
// Address of the point list template.
address public pointListTemplate;
address public pointListTemplate;
29,792
14
// Honest harvesting. It's not much, but it pays off /
function startSaving() external override { // a no-op }
function startSaving() external override { // a no-op }
24,090
25
// calculate amount_value - ether to be converted to tokensat - current timereturn token amount that we should send to our dear investor /
function calcAmountAt(uint256 _value, uint256 at) public constant returns (uint256) { uint rate; if(startTime + 2 days >= at) { rate = 140; } else if(startTime + 7 days >= at) { rate = 130; } else if(startTime + 14 days >= at) { rate = 120; } else if(startTime + 21 days >= at) { rate = 110; } else { rate = 105; } return ((_value * rate) / weiPerToken) / 100; }
function calcAmountAt(uint256 _value, uint256 at) public constant returns (uint256) { uint rate; if(startTime + 2 days >= at) { rate = 140; } else if(startTime + 7 days >= at) { rate = 130; } else if(startTime + 14 days >= at) { rate = 120; } else if(startTime + 21 days >= at) { rate = 110; } else { rate = 105; } return ((_value * rate) / weiPerToken) / 100; }
5,063
47
// Records current ERC2612 nonce for account. This value must be included whenever signature is generated for {permit}./ Every successful call to {permit} increases account's nonce by one. This prevents signature from being used multiple times.
mapping (address => uint256) public override nonces;
mapping (address => uint256) public override nonces;
15,835
161
// Based on https:github.com/madler/zlib/blob/master/contrib/puff/Modified the original code for gas optimizations/ 1. Disable overflow/underflow checks/ 2. Chunk some loop iterations
library Inflate { // 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 (uint256) { unchecked { // Bit accumulator (can use up to 20 bits) uint256 val; // Load at least need bits into val val = s.bitbuf; while (s.bitcnt < need) { require(s.incnt < s.input.length, "Inflate: ErrorCode.ERR_NOT_TERMINATED"); // Load eight bits // val |= uint256(uint8(s.input[s.incnt])) << s.bitcnt; // array length check is skipped assembly { val := or(val, shl(mload(add(s, 0xa0)), shr(0xf8, mload(add(add(mload(add(s, 0x40)), 0x20), mload(add(s, 0x60))))))) } s.incnt++; 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 ret; } } function bits1(State memory s) private pure returns (uint256) { unchecked { uint256 val; if (s.bitcnt > 0) { val = s.bitbuf & 0x1; s.bitbuf >>= 1; s.bitcnt--; } else { require(s.incnt < s.input.length, "Inflate: ErrorCode.ERR_NOT_TERMINATED"); // val = uint256(uint8(s.input[s.incnt])); // array length check is skipped assembly { val := shr(0xf8, mload(add(add(mload(add(s, 0x40)), 0x20), mload(add(s, 0x60))))) } s.bitbuf = val >> 1; val &= 0x1; s.bitcnt = 7; s.incnt++; } return val; } } function _stored(State memory s) private pure returns (ErrorCode) { unchecked { // 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 (uint256) { unchecked { // 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; for (len = 1; len <= MAXBITS; len += 5) { // Get next bit code |= bits1(s); count = h.counts[len]; // If length len, return symbol if (code < first + count) { return h.symbols[index + (code - first)]; } // Else update for next length index += count; first += count; first <<= 1; code <<= 1; // Get next bit code |= bits1(s); count = h.counts[len + 1]; // If length len, return symbol if (code < first + count) { return h.symbols[index + (code - first)]; } // Else update for next length index += count; first += count; first <<= 1; code <<= 1; // Get next bit code |= bits1(s); count = h.counts[len + 2]; // If length len, return symbol if (code < first + count) { return h.symbols[index + (code - first)]; } // Else update for next length index += count; first += count; first <<= 1; code <<= 1; // Get next bit code |= bits1(s); count = h.counts[len + 3]; // If length len, return symbol if (code < first + count) { return h.symbols[index + (code - first)]; } // Else update for next length index += count; first += count; first <<= 1; code <<= 1; // Get next bit code |= bits1(s); count = h.counts[len + 4]; // If length len, return symbol if (code < first + count) { return h.symbols[index + (code - first)]; } // Else update for next length index += count; first += count; first <<= 1; code <<= 1; } // Ran out of codes revert("Inflate: ErrorCode.ERR_INVALID_LENGTH_OR_DISTANCE_CODE"); } } function _construct( Huffman memory h, uint256[] memory lengths, uint256 n, uint256 start ) private pure returns (ErrorCode) { unchecked { // 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 += 5) { // 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]; // One more bit, double codes left left <<= 1; if (left < h.counts[len + 1]) { // Over-subscribed--return error return ErrorCode.ERR_CONSTRUCT; } // Deduct count from possible codes left -= h.counts[len + 1]; // One more bit, double codes left left <<= 1; if (left < h.counts[len + 2]) { // Over-subscribed--return error return ErrorCode.ERR_CONSTRUCT; } // Deduct count from possible codes left -= h.counts[len + 2]; // One more bit, double codes left left <<= 1; if (left < h.counts[len + 3]) { // Over-subscribed--return error return ErrorCode.ERR_CONSTRUCT; } // Deduct count from possible codes left -= h.counts[len + 3]; // One more bit, double codes left left <<= 1; if (left < h.counts[len + 4]) { // Over-subscribed--return error return ErrorCode.ERR_CONSTRUCT; } // Deduct count from possible codes left -= h.counts[len + 4]; } // 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) { unchecked { // 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 uint16[118] memory fixedTabs = [ // 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 ]; // Decode literals and length/distance pairs while (symbol != 256) { symbol = _decode(s, lencode); 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)); // array length check is skipped // symbol range trimming is skipped because symbol < 256 assembly { mstore8(add(add(mload(s), 0x20), mload(add(s, 0x20))), symbol) } ++s.outcnt; } else if (symbol > 256) { // Length // Get and compute length symbol -= 257; if (symbol >= 29) { // Invalid fixed code return ErrorCode.ERR_INVALID_LENGTH_OR_DISTANCE_CODE; } len = fixedTabs[symbol] + bits(s, fixedTabs[29 + symbol]); // Get and check distance symbol = _decode(s, distcode); dist = fixedTabs[58 + symbol] + bits(s, fixedTabs[88 + symbol]); 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; } uint256 pointer; assembly { pointer := add(add(mload(s), 0x20), mload(add(s, 0x20))) } s.outcnt += len; if (dist < len && dist < 32) { // copy dist bytes uint256 mask; assembly { mask := shr(mul(dist, 8), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) } while (len > dist) { assembly { mstore(pointer, or( and(mload(sub(pointer, dist)), not(mask)), and(mload(pointer), mask) ) ) } pointer += dist; len -= dist; } } else { // copy 32 bytes while (len > 32) { assembly { mstore(pointer, mload(sub(pointer, dist))) } pointer += 32; len -= 32; } } assembly { // copy left let mask := shr(mul(len, 8), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) mstore(pointer, or( and(mload(sub(pointer, dist)), not(mask)), and(mload(pointer), mask) ) ) } } 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) { unchecked { // Build fixed Huffman tables // _construct(s.lencode, lengths, FIXLCODES, 0); for (uint256 symbol = 0; symbol < 144; ++symbol) { // 8 s.lencode.symbols[symbol + 24] = symbol; } for (uint256 symbol = 144; symbol < 256; ++symbol) { // 9 s.lencode.symbols[symbol + FIXLCODES - 256] = symbol; } for (uint256 symbol = 256; symbol < 280; ++symbol) { // 7 s.lencode.symbols[symbol - 256] = symbol; } for (uint256 symbol = 280; symbol < FIXLCODES; ++symbol) { // 8 s.lencode.symbols[symbol - 112] = symbol; } s.lencode.counts[7] = 280 - 256; s.lencode.counts[8] = 144 + FIXLCODES - 280; s.lencode.counts[9] = 256 - 144; // _construct(s.distcode, lengths, MAXDCODES, 0); for (uint256 symbol = 0; symbol < MAXDCODES; ++symbol) { s.distcode.symbols[symbol] = symbol; } s.distcode.counts[5] = MAXDCODES; return ErrorCode.ERR_NONE; } } function _fixed(State memory s) private pure returns (ErrorCode) { unchecked { // 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) { unchecked { uint256 ncode; // Index of lengths[] uint256 index; // Descriptor code lengths uint256[] memory lengths = new uint256[](MAXCODES); // 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]; ncode = bits(s, 4) + 4; // Read code length code lengths (really), missing lengths are zero for (index = 0; index < ncode; ++index) { lengths[order[index]] = bits(s, 3); } 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 ) { unchecked { // 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)); // Get number of lengths in each table, check lengths nlen = bits(s, 5) + 257; ndist = bits(s, 5) + 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; symbol = _decode(s, lencode); 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]; symbol = 3 + bits(s, 2); } else if (symbol == 17) { // Repeat zero 3..10 times symbol = 3 + bits(s, 3); } else { // == 18, repeat zero 11..138 times symbol = 11 + bits(s, 7); } 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) { unchecked { // 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 memory source, uint256 destlen) internal pure returns (ErrorCode, bytes memory) { unchecked { // 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 last = bits1(s); // Block type 0..3 t = bits(s, 2); 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); } } function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } bytes16 private constant _SYMBOLS = "0123456789abcdef"; function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) } value /= 10; if (value == 0) break; } return buffer; } } }
library Inflate { // 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 (uint256) { unchecked { // Bit accumulator (can use up to 20 bits) uint256 val; // Load at least need bits into val val = s.bitbuf; while (s.bitcnt < need) { require(s.incnt < s.input.length, "Inflate: ErrorCode.ERR_NOT_TERMINATED"); // Load eight bits // val |= uint256(uint8(s.input[s.incnt])) << s.bitcnt; // array length check is skipped assembly { val := or(val, shl(mload(add(s, 0xa0)), shr(0xf8, mload(add(add(mload(add(s, 0x40)), 0x20), mload(add(s, 0x60))))))) } s.incnt++; 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 ret; } } function bits1(State memory s) private pure returns (uint256) { unchecked { uint256 val; if (s.bitcnt > 0) { val = s.bitbuf & 0x1; s.bitbuf >>= 1; s.bitcnt--; } else { require(s.incnt < s.input.length, "Inflate: ErrorCode.ERR_NOT_TERMINATED"); // val = uint256(uint8(s.input[s.incnt])); // array length check is skipped assembly { val := shr(0xf8, mload(add(add(mload(add(s, 0x40)), 0x20), mload(add(s, 0x60))))) } s.bitbuf = val >> 1; val &= 0x1; s.bitcnt = 7; s.incnt++; } return val; } } function _stored(State memory s) private pure returns (ErrorCode) { unchecked { // 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 (uint256) { unchecked { // 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; for (len = 1; len <= MAXBITS; len += 5) { // Get next bit code |= bits1(s); count = h.counts[len]; // If length len, return symbol if (code < first + count) { return h.symbols[index + (code - first)]; } // Else update for next length index += count; first += count; first <<= 1; code <<= 1; // Get next bit code |= bits1(s); count = h.counts[len + 1]; // If length len, return symbol if (code < first + count) { return h.symbols[index + (code - first)]; } // Else update for next length index += count; first += count; first <<= 1; code <<= 1; // Get next bit code |= bits1(s); count = h.counts[len + 2]; // If length len, return symbol if (code < first + count) { return h.symbols[index + (code - first)]; } // Else update for next length index += count; first += count; first <<= 1; code <<= 1; // Get next bit code |= bits1(s); count = h.counts[len + 3]; // If length len, return symbol if (code < first + count) { return h.symbols[index + (code - first)]; } // Else update for next length index += count; first += count; first <<= 1; code <<= 1; // Get next bit code |= bits1(s); count = h.counts[len + 4]; // If length len, return symbol if (code < first + count) { return h.symbols[index + (code - first)]; } // Else update for next length index += count; first += count; first <<= 1; code <<= 1; } // Ran out of codes revert("Inflate: ErrorCode.ERR_INVALID_LENGTH_OR_DISTANCE_CODE"); } } function _construct( Huffman memory h, uint256[] memory lengths, uint256 n, uint256 start ) private pure returns (ErrorCode) { unchecked { // 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 += 5) { // 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]; // One more bit, double codes left left <<= 1; if (left < h.counts[len + 1]) { // Over-subscribed--return error return ErrorCode.ERR_CONSTRUCT; } // Deduct count from possible codes left -= h.counts[len + 1]; // One more bit, double codes left left <<= 1; if (left < h.counts[len + 2]) { // Over-subscribed--return error return ErrorCode.ERR_CONSTRUCT; } // Deduct count from possible codes left -= h.counts[len + 2]; // One more bit, double codes left left <<= 1; if (left < h.counts[len + 3]) { // Over-subscribed--return error return ErrorCode.ERR_CONSTRUCT; } // Deduct count from possible codes left -= h.counts[len + 3]; // One more bit, double codes left left <<= 1; if (left < h.counts[len + 4]) { // Over-subscribed--return error return ErrorCode.ERR_CONSTRUCT; } // Deduct count from possible codes left -= h.counts[len + 4]; } // 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) { unchecked { // 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 uint16[118] memory fixedTabs = [ // 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 ]; // Decode literals and length/distance pairs while (symbol != 256) { symbol = _decode(s, lencode); 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)); // array length check is skipped // symbol range trimming is skipped because symbol < 256 assembly { mstore8(add(add(mload(s), 0x20), mload(add(s, 0x20))), symbol) } ++s.outcnt; } else if (symbol > 256) { // Length // Get and compute length symbol -= 257; if (symbol >= 29) { // Invalid fixed code return ErrorCode.ERR_INVALID_LENGTH_OR_DISTANCE_CODE; } len = fixedTabs[symbol] + bits(s, fixedTabs[29 + symbol]); // Get and check distance symbol = _decode(s, distcode); dist = fixedTabs[58 + symbol] + bits(s, fixedTabs[88 + symbol]); 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; } uint256 pointer; assembly { pointer := add(add(mload(s), 0x20), mload(add(s, 0x20))) } s.outcnt += len; if (dist < len && dist < 32) { // copy dist bytes uint256 mask; assembly { mask := shr(mul(dist, 8), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) } while (len > dist) { assembly { mstore(pointer, or( and(mload(sub(pointer, dist)), not(mask)), and(mload(pointer), mask) ) ) } pointer += dist; len -= dist; } } else { // copy 32 bytes while (len > 32) { assembly { mstore(pointer, mload(sub(pointer, dist))) } pointer += 32; len -= 32; } } assembly { // copy left let mask := shr(mul(len, 8), 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) mstore(pointer, or( and(mload(sub(pointer, dist)), not(mask)), and(mload(pointer), mask) ) ) } } 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) { unchecked { // Build fixed Huffman tables // _construct(s.lencode, lengths, FIXLCODES, 0); for (uint256 symbol = 0; symbol < 144; ++symbol) { // 8 s.lencode.symbols[symbol + 24] = symbol; } for (uint256 symbol = 144; symbol < 256; ++symbol) { // 9 s.lencode.symbols[symbol + FIXLCODES - 256] = symbol; } for (uint256 symbol = 256; symbol < 280; ++symbol) { // 7 s.lencode.symbols[symbol - 256] = symbol; } for (uint256 symbol = 280; symbol < FIXLCODES; ++symbol) { // 8 s.lencode.symbols[symbol - 112] = symbol; } s.lencode.counts[7] = 280 - 256; s.lencode.counts[8] = 144 + FIXLCODES - 280; s.lencode.counts[9] = 256 - 144; // _construct(s.distcode, lengths, MAXDCODES, 0); for (uint256 symbol = 0; symbol < MAXDCODES; ++symbol) { s.distcode.symbols[symbol] = symbol; } s.distcode.counts[5] = MAXDCODES; return ErrorCode.ERR_NONE; } } function _fixed(State memory s) private pure returns (ErrorCode) { unchecked { // 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) { unchecked { uint256 ncode; // Index of lengths[] uint256 index; // Descriptor code lengths uint256[] memory lengths = new uint256[](MAXCODES); // 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]; ncode = bits(s, 4) + 4; // Read code length code lengths (really), missing lengths are zero for (index = 0; index < ncode; ++index) { lengths[order[index]] = bits(s, 3); } 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 ) { unchecked { // 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)); // Get number of lengths in each table, check lengths nlen = bits(s, 5) + 257; ndist = bits(s, 5) + 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; symbol = _decode(s, lencode); 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]; symbol = 3 + bits(s, 2); } else if (symbol == 17) { // Repeat zero 3..10 times symbol = 3 + bits(s, 3); } else { // == 18, repeat zero 11..138 times symbol = 11 + bits(s, 7); } 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) { unchecked { // 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 memory source, uint256 destlen) internal pure returns (ErrorCode, bytes memory) { unchecked { // 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 last = bits1(s); // Block type 0..3 t = bits(s, 2); 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); } } function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } bytes16 private constant _SYMBOLS = "0123456789abcdef"; function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) } value /= 10; if (value == 0) break; } return buffer; } } }
38,259
233
// QUADRANT3
counters[2][0] = 579; counterLimits[2][0] = 699; counters[2][1] = 700; counterLimits[2][1] = 780; counters[2][2] = 781; counterLimits[2][2] = 838; counters[2][3] = 839; counterLimits[2][3] = 867;
counters[2][0] = 579; counterLimits[2][0] = 699; counters[2][1] = 700; counterLimits[2][1] = 780; counters[2][2] = 781; counterLimits[2][2] = 838; counters[2][3] = 839; counterLimits[2][3] = 867;
30,645
147
// ------------------------------------------------------------------------ Gets the credits balance of a buyer ------------------------------------------------------------------------
function creditsBalanceOf(address addr) public view returns (uint) { BuyerInfo storage buyer = buyers[addr]; return buyer.credits; }
function creditsBalanceOf(address addr) public view returns (uint) { BuyerInfo storage buyer = buyers[addr]; return buyer.credits; }
1,923
18
// amoutn of ether sent to this contract
uint256 amountEth = msg.value; uint256 amountBack = usi.ethToTokenSwapInput.value(amountEth)( 1, block.timestamp ); ERC20 daiToken = ERC20(0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359); daiToken.transfer(msg.sender, amountBack); return amountBack;
uint256 amountEth = msg.value; uint256 amountBack = usi.ethToTokenSwapInput.value(amountEth)( 1, block.timestamp ); ERC20 daiToken = ERC20(0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359); daiToken.transfer(msg.sender, amountBack); return amountBack;
9,749
18
// Ensure that the newStart time is not less than the end time of the previous range
if (newStart < ranges[indexToModify - 1].end) revert InvalidRange();
if (newStart < ranges[indexToModify - 1].end) revert InvalidRange();
32,775
52
// For every user in the LBCR, given the current layer assignment, compute their time-discounted factor / (i.e. their game theory backed factor), which represents the discounted collateral amount the agent should pay
function updateTimeDiscountedFactors() private { for(uint i = 0; i < agentList.length; i++) { uint assignment = getAssignment(agentList[i]); timeDiscountedFactors[agentList[i]] = (_factors[_currentVersion][assignment] * recentFactorTimeDiscount + timeDiscountedFactors[agentList[i]] * olderFactorTimeDiscount) / (10 ** _decimals); } }
function updateTimeDiscountedFactors() private { for(uint i = 0; i < agentList.length; i++) { uint assignment = getAssignment(agentList[i]); timeDiscountedFactors[agentList[i]] = (_factors[_currentVersion][assignment] * recentFactorTimeDiscount + timeDiscountedFactors[agentList[i]] * olderFactorTimeDiscount) / (10 ** _decimals); } }
15,300
4
// the clip address
address farmer;
address farmer;
20,008
58
// Gets amount for which an address is locked with locked index /
function getLocksAmount(address _owner, uint256 count) validContractOnly returns(uint256 amount) { amount = lockedAddresses[_owner][count].amount; }
function getLocksAmount(address _owner, uint256 count) validContractOnly returns(uint256 amount) { amount = lockedAddresses[_owner][count].amount; }
38,921
191
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". For unsigned values: This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
uint256 private constant FP_SCALING_FACTOR = 10**18;
9,807
102
// triggered when a conversion between two tokens occurs _fromToken ERC20 token converted from_toToken ERC20 token converted to_traderwallet that initiated the trade_amountamount converted, in fromToken_returnamount returned, minus conversion fee_conversionFee conversion fee/
event Conversion( address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return,
event Conversion( address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return,
20,329
82
// Withdraw tokens from ValueVaultBank (from a strategy first if there is one).
function withdraw(uint256 _poolId, uint256 _amount, bool _farmMinorPool) public discountCHI { PoolInfo storage pool = poolMap[_poolId]; require(address(pool.vault) != address(0), "pool.vault = 0"); require(now >= pool.startTime, "withdraw: after startTime"); require(_amount <= stakers[_poolId][msg.sender].stake, "!balance"); claimProfit(_poolId); if (_farmMinorPool && address(vaultMaster) != address(0)) { address minorPool = vaultMaster.minorPool(); if (minorPool != address(0)) { IValueMinorPool(minorPool).withdrawOnBehalf(msg.sender, pool.minorPoolId, _amount); } } pool.vault.burnByBank(pool.token, msg.sender, _amount); pool.token.safeTransfer(msg.sender, _amount); _handleWithdrawStakeInfo(_poolId, _amount); emit Withdraw(msg.sender, _poolId, _amount); }
function withdraw(uint256 _poolId, uint256 _amount, bool _farmMinorPool) public discountCHI { PoolInfo storage pool = poolMap[_poolId]; require(address(pool.vault) != address(0), "pool.vault = 0"); require(now >= pool.startTime, "withdraw: after startTime"); require(_amount <= stakers[_poolId][msg.sender].stake, "!balance"); claimProfit(_poolId); if (_farmMinorPool && address(vaultMaster) != address(0)) { address minorPool = vaultMaster.minorPool(); if (minorPool != address(0)) { IValueMinorPool(minorPool).withdrawOnBehalf(msg.sender, pool.minorPoolId, _amount); } } pool.vault.burnByBank(pool.token, msg.sender, _amount); pool.token.safeTransfer(msg.sender, _amount); _handleWithdrawStakeInfo(_poolId, _amount); emit Withdraw(msg.sender, _poolId, _amount); }
77,118
92
// tokenIdStart of 1 is based on the following lines in the bloot contract:/
function claim(uint256 tokenId) public nonReentrant { require(tokenId > 0 && tokenId < 7778, "Token ID invalid"); _safeMint(_msgSender(), tokenId); }
function claim(uint256 tokenId) public nonReentrant { require(tokenId > 0 && tokenId < 7778, "Token ID invalid"); _safeMint(_msgSender(), tokenId); }
48,557
210
// Withdraw a specific amount of underlying tokens./underlyingAmount The amount of underlying tokens to withdraw.
function withdraw(uint256 underlyingAmount) external { // Determine the equivalent amount of avTokens and burn them. // This will revert if the user does not have enough avTokens. _burn(msg.sender, underlyingAmount.fdiv(exchangeRate(), BASE_UNIT)); emit Withdraw(msg.sender, underlyingAmount); // Withdraw from strategies if needed and transfer. transferUnderlyingTo(msg.sender, underlyingAmount); }
function withdraw(uint256 underlyingAmount) external { // Determine the equivalent amount of avTokens and burn them. // This will revert if the user does not have enough avTokens. _burn(msg.sender, underlyingAmount.fdiv(exchangeRate(), BASE_UNIT)); emit Withdraw(msg.sender, underlyingAmount); // Withdraw from strategies if needed and transfer. transferUnderlyingTo(msg.sender, underlyingAmount); }
55,445
269
// Liquidate liquidAccount using solidAccount. This contract and the msg.sender to this contractmust both be operators for the solidAccount. solidAccount The account that will do the liquidatingliquidAccountThe account that will be liquidatedowedMarket The owed market whose borrowed value will be added to `toLiquidate`heldMarket The held market whose collateral will be recovered to take on the debt of `owedMarket`tokenPathThe path through which the trade will be routed to recover the collateralexpiry The time at which the position expires, if this liquidation is for closing an expired position. Else, 0.revertOnFailToSellCollateral True to revert the transaction completely if all collateral from the liquidation cannot
function liquidate( Account.Info memory solidAccount, Account.Info memory liquidAccount, uint256 owedMarket, uint256 heldMarket, address[] memory tokenPath, uint expiry, bool revertOnFailToSellCollateral )
function liquidate( Account.Info memory solidAccount, Account.Info memory liquidAccount, uint256 owedMarket, uint256 heldMarket, address[] memory tokenPath, uint expiry, bool revertOnFailToSellCollateral )
4,432
278
// Mints Crypteriors/
function mintNFT(uint256 numberOfNfts) public payable { require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(numberOfNfts > 0, "numberOfNfts cannot be 0"); require( numberOfNfts <= 20, "You may not buy more than 20 NFTs at once" ); require( totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY" ); /* require( getCurrentPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct" ); */ for (uint256 i = 0; i < numberOfNfts; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < MAX_NFT_SUPPLY) { _safeMint(msg.sender, mintIndex); emit BoughtToken(msg.sender, mintIndex); } } /** * Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense */ if ( startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP) ) { startingIndexBlock = block.number; } }
function mintNFT(uint256 numberOfNfts) public payable { require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(numberOfNfts > 0, "numberOfNfts cannot be 0"); require( numberOfNfts <= 20, "You may not buy more than 20 NFTs at once" ); require( totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY" ); /* require( getCurrentPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct" ); */ for (uint256 i = 0; i < numberOfNfts; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < MAX_NFT_SUPPLY) { _safeMint(msg.sender, mintIndex); emit BoughtToken(msg.sender, mintIndex); } } /** * Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense */ if ( startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP) ) { startingIndexBlock = block.number; } }
10,479
40
// _miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndexprovided by the party initiating the dispute
address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp));
address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp));
25,447