Warning! Contract bytecode has been changed and doesn't match the verified one. Therefore, interaction with this smart contract may be risky.
This contract has been verified via Sourcify.
View contract in Sourcify repository
- Contract name:
- Jackpot
- Optimization enabled
- true
- Compiler version
- v0.8.24+commit.e11b9ed9
- Optimization runs
- 200
- EVM Version
- paris
- Verified at
- 2026-03-19T14:19:18.582965Z
src/ERA3/Jackpot/Jackpot.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import {Dark} from "@era2/Dark.sol";
import {FuelCell} from "../FuelCell/FuelCell.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {MerkleProofLib} from "@solady/src/utils/MerkleProofLib.sol";
import {JourneyPhaseManager} from "../JourneyPhaseManager/JourneyPhaseManager.sol";
import {ERA3Constants} from "../constants/ERA3Constants.sol";
import {JackpotStorage} from "./JackpotStorage.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
contract Jackpot is
Ownable2StepUpgradeable,
ReentrancyGuardUpgradeable,
ERA3Constants,
UUPSUpgradeable,
JackpotStorage
{
event KeeperUpdated(address newKeeper);
event BonusAdded(address indexed sender, uint256 bonusAmount);
event LotterResultAnnounced(
uint16 indexed journey, uint16 indexed lottery, uint256 numberOfWinners, uint256 payout
);
event WinningPruned(uint256 indexed tokenId, uint16 journeyId, uint16 lotteryId, uint256 winningAmount);
error EmptyUri();
error EmptyRoot();
error ZeroKeeperAddress();
error ZeroBonusNotAllowed();
error AllLotteryConducted();
error ArrayLengthMismatch();
error LotteryForZeroJourney();
error LotteryForZeroLotteryId();
error CannotRolloverEmptyBonus();
error CanPruneForSameAddressOnly();
error WaitForCurrentJourneyBonusToBeUsed();
error UnauthorizedKeeper(address unknownKeeper);
error AlreadyClaimed(uint256 tokenId, uint16 journeyId);
error ZeroWinnersForLottery(uint16 journeyId, uint16 lotteryId);
error JourneyInFuture(uint16 journeyId, uint16 currentJourneyId);
error LotteryAlreadyConducted(uint16 journeyId, uint16 lotteryId);
error LotteryNonSequential(uint16 lotteryId, uint16 nextLotteryId);
error LotteryPhaseNotActive(uint16 lotteryId, uint256 currentPhase);
error NotAWinner(uint256 tokenId, uint16 journeyId, uint16 lotteryId);
error PayoutGreaterThanBalance(uint256 expectedLotteryPayout, uint256 jackpotAvailableBalance);
modifier onlyKeeper() {
if (msg.sender != keeper) revert UnauthorizedKeeper(msg.sender);
_;
}
constructor() {
_disableInitializers();
}
function initialize(
Dark _darkToken,
FuelCell _fuelCellsToken,
JourneyPhaseManager _jpm,
address _keeper,
address _initialOwner
) external initializer {
__ReentrancyGuard_init();
__Ownable2Step_init();
_transferOwnership(_initialOwner);
darkToken = _darkToken;
fuelCellsToken = _fuelCellsToken;
jpm = _jpm;
keeper = _keeper;
}
function setKeeper(address _keeper) external onlyOwner {
if (_keeper == address(0)) revert ZeroKeeperAddress();
keeper = _keeper;
emit KeeperUpdated(_keeper);
}
function isWinner(PruneWinning calldata winning) public view returns (bool) {
// generate leaf
bytes32 leaf = keccak256(abi.encodePacked(winning.tokenId, winning.journeyId, winning.lotteryId));
// validate proofs
bytes32 root = lotteryPayouts[winning.journeyId][winning.lotteryId].root;
return MerkleProofLib.verifyCalldata(winning.proofs, root, leaf);
}
function announceLotteryResult(LotteryResult calldata _result) external onlyKeeper nonReentrant {
// checks
// zero input validations
if (_result.journeyId == 0) revert LotteryForZeroJourney();
if (_result.lotteryId == 0) revert LotteryForZeroLotteryId();
if (_result.root == bytes32(0)) revert EmptyRoot();
if (_result.numberOfWinners == 0) revert ZeroWinnersForLottery(_result.journeyId, _result.lotteryId);
// logical validations
if (currentLotteryId[_result.journeyId] == LOTTERIES_PER_JOURNEY) revert AllLotteryConducted();
if (lotteryPayouts[_result.journeyId][_result.lotteryId].numberOfWinners != 0) {
revert LotteryAlreadyConducted(_result.journeyId, _result.lotteryId);
}
if (currentLotteryId[_result.journeyId] + 1 != _result.lotteryId) {
revert LotteryNonSequential(_result.lotteryId, currentLotteryId[_result.journeyId] + 1);
}
uint256 bonusAmount = bonus;
// update state
// increment the lottery ID
currentLotteryId[_result.journeyId] += 1;
// more logical validations
if (jpm.currentJourney() < _result.journeyId) {
revert JourneyInFuture(_result.journeyId, uint16(jpm.currentJourney()));
}
if (jpm.currentPhase() == JOURNEY_PHASE_1) {
revert LotteryPhaseNotActive(_result.lotteryId, uint16(jpm.currentPhase()));
}
// calculate payout
uint256 jackpotBalance = darkToken.balanceOf(address(this)) - totalPendingPayout - bonusAmount; // external call to trusted contract
uint256 currentLotteryPayout = _calculateLotteryPayout(_result.lotteryId, jackpotBalance);
if (bonusAmount != 0) {
currentLotteryPayout = currentLotteryPayout + bonusAmount;
delete bonus;
}
if (currentLotteryPayout > jackpotBalance + bonusAmount) {
revert PayoutGreaterThanBalance(currentLotteryPayout, jackpotBalance + bonusAmount);
}
// update state
// update total payout
totalPendingPayout += currentLotteryPayout;
// lottery payout
lotteryPayouts[_result.journeyId][_result.lotteryId] = LotteryPayout({
numberOfWinners: _result.numberOfWinners,
root: _result.root,
uri: _result.uri,
payoutAmount: currentLotteryPayout
});
emit LotterResultAnnounced(_result.journeyId, _result.lotteryId, _result.numberOfWinners, currentLotteryPayout);
}
function depositBonus(uint256 amount) external {
if (amount == 0) revert ZeroBonusNotAllowed();
// add bonus
bonus += amount;
// transfer tokens
darkToken.transferFrom(msg.sender, address(this), amount);
emit BonusAdded(msg.sender, amount);
}
function pruneWinnings(PruneWinning[] calldata _winnings) external {
_prune(_winnings);
}
function _prune(PruneWinning[] calldata _winnings) internal {
uint256 claimAmount;
address owner = fuelCellsToken.ownerOf(_winnings[0].tokenId);
for (uint256 i; i < _winnings.length; i++) {
// ensure the winning hasn't been claimed
if (isClaimed[_winnings[i].tokenId]) revert AlreadyClaimed(_winnings[i].tokenId, _winnings[i].journeyId);
if (fuelCellsToken.ownerOf(_winnings[i].tokenId) != owner) revert CanPruneForSameAddressOnly();
// ensure user is part of the winning
if (!isWinner(_winnings[i])) {
revert NotAWinner(_winnings[i].tokenId, _winnings[i].journeyId, _winnings[i].lotteryId);
}
isClaimed[_winnings[i].tokenId] = true;
// claim
uint256 perTokenShare = _calculatePerTokenShare(_winnings[i].journeyId, _winnings[i].lotteryId);
claimAmount += perTokenShare;
emit WinningPruned(_winnings[i].tokenId, _winnings[i].journeyId, _winnings[i].lotteryId, perTokenShare);
}
totalPendingPayout -= claimAmount;
darkToken.transfer(owner, claimAmount);
}
function _calculatePerTokenShare(uint16 journeyId, uint16 lotteryId) internal view returns (uint256) {
LotteryPayout memory payout = lotteryPayouts[journeyId][lotteryId];
return payout.payoutAmount / payout.numberOfWinners;
}
/**
* Note: Logic to calculate lottery payout is following:
* 1. For each journey, the lottery payout is as follows:
* Total Lottery Payout is the starting balance of jackpot for the current journey after minting phase ends.
* consider the payout for lottery 1 = x1
* consider the payout for lottery 2 = x2
* consider the payout for lottery 3 = x3
* Then, total lottery payout in a journet is x1 + x2 + x3
* 2. At any given point the jackpot contract is not aware of what was the starting balance of the jackpot for the current journey
* 3. Hence, we first calculate the starting balance of the jackpot for the current journey - y1
* 4. Logic of Y1 is:
* - y1 = 100y2 / (100 - a1) = 100y3 / (100 - a1 - a2)
* - where y1 is the jackpot balance in lottery 1
* - where y2 is the jackpot balance in lottery 2
* - where y3 is the jackpot balance in lottery 3
*/
function _calculateLotteryPayout(uint256 lotteryId, uint256 jackpotBalance) private pure returns (uint256) {
uint256 y1Numerator;
uint256 y1Denominator;
uint256 a;
if (lotteryId == 1) {
y1Numerator = jackpotBalance;
y1Denominator = 1;
a = LOTTERY_1_PAYOUT_PERCENTAGE;
} else if (lotteryId == 2) {
y1Numerator = HUNDRED_PERCENT * jackpotBalance;
y1Denominator = HUNDRED_PERCENT - LOTTERY_1_PAYOUT_PERCENTAGE;
a = LOTTERY_2_PAYOUT_PERCENTAGE;
} else {
y1Numerator = HUNDRED_PERCENT * jackpotBalance;
y1Denominator = HUNDRED_PERCENT - LOTTERY_1_PAYOUT_PERCENTAGE - LOTTERY_2_PAYOUT_PERCENTAGE;
a = LOTTERY_3_PAYOUT_PERCENTAGE;
}
// payout
return y1Numerator * a / (HUNDRED_PERCENT * y1Denominator);
}
function _authorizeUpgrade(address newImplementation) internal virtual override onlyOwner {}
}
/IJourneyPhaseManager.sol
pragma solidity 0.8.24;
interface IJourneyPhaseManager {
function isRaptureAlertActive() external view returns (bool);
}
/ERA3Constants.sol
pragma solidity 0.8.24;
contract ERA3Constants {
// General Constants
uint256 public constant HUNDRED_PERCENT = 1000000; // 100 scaled to 4 decimal places
uint16 public constant BASIS_POINTS = 10000;
// Fuel Cell Price
uint256 public constant FUEL_CELL_PRICE = 1e18; // Price per Fuel Cell in Dark tokens
// Journey Related Constants
// Note: Update the durations before deployment
uint256 public constant JOURNEY_PHASE_1 = 1;
uint256 public constant PHASE_1_DURATION = 11 days;
uint256 public constant JOURNEY_1_PHASE_1_DURATION = 16 days;
uint256 public constant JOURNEY_PHASE_2 = 2;
uint256 public constant PHASE_2_DURATION = 33 days + 12 hours;
uint256 public constant JOURNEY_PHASE_3 = 3;
uint256 public constant PHASE_3_DURATION = 12 hours;
uint256 public constant JOURNEY_DURATION = 45 days;
uint256 public constant JOURNEY_1_DURATION = 50 days;
uint256 public constant TOTAL_JOURNEYS = 33;
// Treasury Yield Related constants
uint256 public constant yieldFormulaA = 30000; // scaled to 4 decimal places
uint256 public constant yieldFormulaR = 90; // 0.9 scaled to 2 decimal places
// Lottery Related Constants
// Note: Jackpot contract is sensitive to constants change,
// hence changing constants will require change in implementation logic
uint256 public constant LOTTERIES_PER_JOURNEY = 3;
uint256 public constant LOTTERY_1_PAYOUT_PERCENTAGE = 100000; // 10 scaled to 4 decimal places
uint256 public constant LOTTERY_2_PAYOUT_PERCENTAGE = 300000; // 30 scaled to 4 decimal places
uint256 public constant LOTTERY_3_PAYOUT_PERCENTAGE = 600000; // 60 scaled to 4 decimal places
}
/JourneyPhaseManagerStorage.sol
pragma solidity 0.8.24;
abstract contract JourneyPhaseManagerStorage {
bool public paused;
bool public isRapturePossible;
uint256 public startTime;
uint256 public totalPausedTime;
uint256 public recentPauseStartTime;
address public fuelcell;
mapping(uint256 journeyId => uint256 startTokenId) public startTokenIdInJourney;
mapping(uint256 journeyId => uint256 lastTokenId) public lastTokenIdInJourney;
mapping(uint256 journeyId => uint256 numberOfTokens) public tokensBurnedFromJourney;
// gap for future states
uint256[50] private _gap;
}
/JourneyPhaseManager.sol
pragma solidity 0.8.24;
import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import {ERA3Constants} from "../constants/ERA3Constants.sol";
import {JourneyPhaseManagerStorage} from "./JourneyPhaseManagerStorage.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
contract JourneyPhaseManager is Ownable2StepUpgradeable, ERA3Constants, UUPSUpgradeable, JourneyPhaseManagerStorage {
event JourneyStarted(uint256 journey, uint256 timestamp);
event PhaseIncremented(uint256 journey, uint256 phase, uint256 timestamp);
event RaptureAlertDetectionActivated();
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
event FuelCellUpdated(address newFuelCell);
error AlreadyPaused();
error AlreadyUnpaused();
error InvalidFuelCell();
error OnlyAllowedFromFuelCells();
error EndTokenIDCannotBeLowerThanStartTokenId();
modifier onlyFuelCells() {
if (msg.sender != fuelcell) {
revert OnlyAllowedFromFuelCells();
}
_;
}
constructor() {
_disableInitializers();
}
function initialize(address _initialOwner, address _fuelCell) external initializer {
__Ownable2Step_init();
_transferOwnership(_initialOwner);
startTime = block.timestamp;
fuelcell = _fuelCell;
emit JourneyStarted(1, startTime);
}
function setFuelCell(address _newFewCell) external onlyOwner {
if (_newFewCell == address(0)) {
revert InvalidFuelCell();
}
fuelcell = _newFewCell;
emit FuelCellUpdated(_newFewCell);
}
function pause() public onlyOwner {
if (paused) revert AlreadyPaused();
recentPauseStartTime = block.timestamp;
paused = true;
emit Paused(msg.sender);
}
function unpause() public onlyOwner {
if (!paused) revert AlreadyUnpaused();
totalPausedTime += block.timestamp - recentPauseStartTime;
recentPauseStartTime = 0;
paused = false;
emit Unpaused(msg.sender);
}
function activateRapture() public onlyOwner {
isRapturePossible = true;
emit RaptureAlertDetectionActivated();
}
function isMintingActive() public view returns (bool) {
return currentPhase() == 1 && !paused && currentJourney() <= TOTAL_JOURNEYS;
}
function validateJourneyId(uint256 fuelCellId, uint256 journeyId) public view returns (bool) {
return startTokenIdInJourney[journeyId] <= fuelCellId && fuelCellId <= lastTokenIdInJourney[journeyId];
}
function tokenBurned(uint256 journeyId) public onlyFuelCells {
tokensBurnedFromJourney[journeyId] += 1;
}
function getActiveNftsInJourney(uint256 journeyId) public view returns (uint256) {
if (startTokenIdInJourney[journeyId] == 0) return 0;
return
lastTokenIdInJourney[journeyId] - startTokenIdInJourney[journeyId] + 1 - tokensBurnedFromJourney[journeyId];
}
function currentJourney() public view returns (uint256) {
if (_getElapsedTime() < JOURNEY_1_DURATION) return 1;
return (_getElapsedTime() - JOURNEY_1_DURATION) / _getJourneyDuration() + 2;
}
function currentPhase() public view returns (uint256) {
uint256 journeyElapsedTime = _getJourneyElapsedTime();
uint256 phase1Duration = _getPhaseOneDuration();
if (journeyElapsedTime < phase1Duration) {
return 1;
} else if (journeyElapsedTime < phase1Duration + PHASE_2_DURATION) {
return 2;
} else {
return 3;
}
}
function getNextPhaseTimestamp() public view returns (uint256) {
uint256 journeyElapsedTime = _getJourneyElapsedTime();
uint256 phase1Duration = _getPhaseOneDuration();
if (journeyElapsedTime < phase1Duration) {
return block.timestamp + phase1Duration - journeyElapsedTime;
} else if (journeyElapsedTime < phase1Duration + PHASE_2_DURATION) {
return block.timestamp + phase1Duration + PHASE_2_DURATION - journeyElapsedTime;
} else {
return block.timestamp + _getJourneyDuration() - journeyElapsedTime;
}
}
function getNextJourneyTimestamp() public view returns (uint256) {
uint256 journeyElapsedTime = _getJourneyElapsedTime();
return block.timestamp + _getJourneyDuration() - journeyElapsedTime;
}
function registerTokenIdForJourney(uint256 nextTokenId, uint256 endTokenId) public onlyFuelCells {
if (endTokenId < nextTokenId) revert EndTokenIDCannotBeLowerThanStartTokenId();
uint256 currentJourneyId = currentJourney();
if (startTokenIdInJourney[currentJourneyId] == 0) {
startTokenIdInJourney[currentJourneyId] = nextTokenId;
}
lastTokenIdInJourney[currentJourneyId] = endTokenId;
}
function totalNFTsInJourney(uint256 _journey) public view returns (uint256) {
uint256 startTokenId = startTokenIdInJourney[_journey];
uint256 endTokenId = lastTokenIdInJourney[_journey];
return endTokenId - startTokenId + 1;
}
function isRaptureAlertActive() external view returns (bool) {
if (!isRapturePossible) return false;
uint256 currJourney = currentJourney();
return (currJourney > TOTAL_JOURNEYS) || (currJourney == TOTAL_JOURNEYS && currentPhase() == 3);
}
function _getElapsedTime() internal view returns (uint256) {
if (paused) {
return recentPauseStartTime - startTime - totalPausedTime;
} else {
return block.timestamp - startTime - totalPausedTime;
}
}
function _getJourneyElapsedTime() internal view returns (uint256) {
uint256 elapsedTime = _getElapsedTime();
if (elapsedTime >= JOURNEY_1_DURATION) {
elapsedTime = elapsedTime - JOURNEY_1_DURATION;
return elapsedTime % JOURNEY_DURATION;
}
return elapsedTime % JOURNEY_1_DURATION;
}
function _getJourneyDuration() private view returns (uint256) {
if (_getElapsedTime() >= JOURNEY_1_DURATION) {
return JOURNEY_DURATION;
} else {
return JOURNEY_1_DURATION;
}
}
function _getPhaseOneDuration() private view returns (uint256) {
if (_getElapsedTime() >= JOURNEY_1_DURATION) {
return PHASE_1_DURATION;
} else {
return JOURNEY_1_PHASE_1_DURATION;
}
}
function _authorizeUpgrade(address newImplementation) internal virtual override onlyOwner {}
}
/JackpotStorage.sol
pragma solidity 0.8.24;
import {Dark} from "@era2/Dark.sol";
import {FuelCell} from "../FuelCell/FuelCell.sol";
import {JourneyPhaseManager} from "../JourneyPhaseManager/JourneyPhaseManager.sol";
abstract contract JackpotStorage {
struct LotteryPayout {
uint256 numberOfWinners;
bytes32 root;
string uri;
uint256 payoutAmount;
}
struct LotteryResult {
uint16 journeyId;
uint16 lotteryId;
uint256 numberOfWinners;
bytes32 root;
string uri;
}
struct PruneWinning {
uint16 journeyId;
uint16 lotteryId;
uint256 tokenId;
bytes32[] proofs;
}
Dark public darkToken;
FuelCell public fuelCellsToken;
JourneyPhaseManager public jpm;
address public keeper;
uint256 public totalPendingPayout;
uint256 public bonus;
// rules:
// - No token ID can win more than one lottery in a journey
mapping(uint256 tokenId => bool) public isClaimed;
mapping(uint16 journeyId => uint16 currentLotteryId) public currentLotteryId;
mapping(uint16 journeyId => mapping(uint16 lotteryId => LotteryPayout payouts)) public lotteryPayouts;
// gap for future states
uint256[50] private _gap;
}
/FuelCellStorage.sol
pragma solidity 0.8.24;
import {JourneyPhaseManager} from "../JourneyPhaseManager/JourneyPhaseManager.sol";
abstract contract FuelCellStorage {
JourneyPhaseManager public journeyPhaseManager;
/// @notice Address of LaunchControlCenter contract
address public launchControlCenter;
address public treasury;
uint256 public nextTokenId;
uint256 public totalSupply;
/// @notice The base URI for the token collection.
string public baseURI;
string public suffix;
// gap for future states
uint256[50] private _gap;
}
/introspection/IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/FuelCell.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import {ERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import {LibString} from "solady/src/utils/LibString.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
import {JourneyPhaseManager} from "../JourneyPhaseManager/JourneyPhaseManager.sol";
import {FuelCellStorage} from "./FuelCellStorage.sol";
/// @title FuelCell Token Contract
/// @notice This contract implements an ERC721 token called FuelCell.
/// @dev Extends ERC721 token standard with minting and burning functionality controlled by the contract owner and a designated LaunchControlCenter.
contract FuelCell is ERC721Upgradeable, Ownable2StepUpgradeable, UUPSUpgradeable, FuelCellStorage {
using LibString for uint256;
event LauncherUpdated(address newLaunchControlCenter);
event UpdatedBaseUri(string newBaseUri);
event UpdatedSuffix(string newSuffix);
event MintFuelCells(
address indexed to, uint256 indexed journeyId, uint256 indexed startTokenId, uint256 lastTokenId
);
/// @dev Custom errors
error NotLauncher();
error NotOwner();
error NotMinted();
error NotTreasury();
error InvalidLaunchControlCenter();
error InvalidInitialOwner();
error InvalidJourneyPhaseManager();
constructor() {
_disableInitializers();
}
/// @param _launchControlCenter Address of the LaunchControlCenter contract.
function initialize(
address _launchControlCenter,
address _initialOwner,
address _treasury,
JourneyPhaseManager _journeyPhaseManager,
string memory _initalBaseUri,
string memory _initialSuffix
) external initializer {
__Ownable2Step_init();
_transferOwnership(_initialOwner);
__ERC721_init("FuelCell", "FUEL");
if (_launchControlCenter == address(0)) revert InvalidLaunchControlCenter();
if (_initialOwner == address(0)) revert InvalidInitialOwner();
if (address(_journeyPhaseManager) == address(0)) revert InvalidJourneyPhaseManager();
launchControlCenter = _launchControlCenter;
journeyPhaseManager = _journeyPhaseManager;
treasury = _treasury;
baseURI = _initalBaseUri;
suffix = _initialSuffix;
nextTokenId = 1;
}
/// @notice Ensures the caller is the LaunchControlCenter
modifier onlyLauncher() {
if (msg.sender != launchControlCenter) revert NotLauncher();
_;
}
modifier onlyTreasury() {
if (msg.sender != treasury) revert NotTreasury();
_;
}
/// @dev Mints a Fuel Cell to a specified address.
/// @notice Only LaunchControlCenter can mint new tokens.
/// @param to The address of the recipient to mint the token to.
function mint(address to, uint256 quantity) external onlyLauncher {
uint256 startTokenId = nextTokenId;
nextTokenId = startTokenId + quantity;
totalSupply = totalSupply + quantity;
uint256 lastTokenIdToBeMinted = startTokenId + quantity - 1;
journeyPhaseManager.registerTokenIdForJourney(startTokenId, lastTokenIdToBeMinted);
for (uint256 i = startTokenId; i <= lastTokenIdToBeMinted; i++) {
_mint(to, i);
}
emit MintFuelCells(to, journeyPhaseManager.currentJourney(), startTokenId, lastTokenIdToBeMinted);
}
/// @dev Burns an existing Fuel Cell token.
/// @param tokenId The ID of the token to be burned.
function burn(uint256 tokenId, uint256 journeyId) external onlyTreasury {
totalSupply = totalSupply - 1;
// when a token is burned, inform JPM that the token was burned
journeyPhaseManager.tokenBurned(journeyId);
_burn(tokenId);
}
/// @dev Updates the address of the LaunchControlCenter.
/// @notice This can only be called by the contract owner.
/// @param _launchControlCenter The new address for the LaunchControlCenter.
function updateLauncherAddress(address _launchControlCenter) external onlyOwner {
if (_launchControlCenter == address(0)) revert InvalidLaunchControlCenter();
launchControlCenter = _launchControlCenter;
emit LauncherUpdated(_launchControlCenter);
}
/// @dev Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) public view virtual override returns (string memory) {
return string(abi.encodePacked(baseURI, id.toString(), suffix));
}
function setBaseUri(string memory _newbaseUri) external onlyOwner {
baseURI = _newbaseUri;
emit UpdatedBaseUri(_newbaseUri);
}
function setSuffix(string memory _newSuffix) external onlyOwner {
suffix = _newSuffix;
emit UpdatedSuffix(_newSuffix);
}
function _authorizeUpgrade(address newImplementation) internal virtual override onlyOwner {}
}
/Dark.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {ERC20} from "@solmate/src/tokens/ERC20.sol";
import {IJourneyPhaseManager} from "@interfaces/IJourneyPhaseManager.sol";
/// @title Dark Token Contract
/// @notice Implementation of the ERC20 Dark token with a capped supply and controlled minting
/// @dev Extends the ERC20 standard
contract Dark is ERC20 {
/// @notice Maximum token supply set to 1 million tokens
uint256 public constant MAX_SUPPLY = 1_000_000 ether;
/// @notice Address authorized to mint new tokens, initially set to the deploying address
address public claimsContract;
mapping(address => bool) public allowlist;
mapping(address => address) public holders;
address internal constant SENTINEL_HOLDERS = address(0x1);
uint256 public holderCount;
address public trustedEntity;
IJourneyPhaseManager public journeyPhaseManager;
bool public raptureOccurred = false;
event AllowlistAdded(address indexed account);
event AllowlistRemoved(address indexed account);
event TrustedEntityUpdated(address indexed previousEntity, address indexed newEntity);
event RaptureOccurred();
event AddedHolder(address indexed holder);
event JourneyPhaseManagerSet(IJourneyPhaseManager indexed journeyPhaseManager);
/// @dev Custom errors
error OvershotSupplyLimit();
error Unauthorized();
error NotYetReachedSupplyLimit();
error AlreadyAllowlisted(address account);
error NotTrustedEntity(address caller);
error TrustedEntityCannotBeEmpty();
error AllowlistedAddressCannotBeZero();
error AlreadyRaptured();
error CannotRaptureBeforeAlert();
error EmptyTrustedEntity();
error EmptyName();
error EmptySymbol();
modifier onlyTrustedEntity() {
if (msg.sender != trustedEntity) {
revert NotTrustedEntity(msg.sender);
}
_;
}
/// @notice Initializes the contract, setting the initial claims contract and token details
/// @param _name The name of the token
/// @param _symbol The symbol of the token
/// @param _trustedEntity The address of the trusted entity
constructor(string memory _name, string memory _symbol, address _trustedEntity) ERC20(_name, _symbol, 18) {
if (bytes(_name).length == 0) revert EmptyName();
if (bytes(_symbol).length == 0) revert EmptySymbol();
if (_trustedEntity == address(0)) {
revert EmptyTrustedEntity();
}
// (Dark, DARK, 18)
claimsContract = msg.sender; // DarkClaims contract
holders[SENTINEL_HOLDERS] = SENTINEL_HOLDERS;
trustedEntity = _trustedEntity;
emit TrustedEntityUpdated(address(0), msg.sender);
}
/// @dev Internal function to safely mint new tokens, ensuring the max supply isn't exceeded
/// @param to The address that will receive the minted tokens
/// @param amount The number of tokens to mint
function _safeMint(address to, uint256 amount) internal {
if (!raptureOccurred) _addHolder(to);
_mint(to, amount);
if (totalSupply > MAX_SUPPLY) revert OvershotSupplyLimit();
}
/// @notice Mints new tokens to a specified address, callable only by the claimsContract
/// @dev Calls the internal _safeMint function for minting
/// @param to The address to mint the tokens to
/// @param amount The amount of tokens to mint
function mint(address to, uint256 amount) public {
if (msg.sender != claimsContract) revert Unauthorized();
_safeMint(to, amount);
}
/// @notice Sets the JourneyPhaseManager contract address
/// @dev Callable only by the trusted entity
/// @param _journeyPhaseManager The address of the JourneyPhaseManager contract
function setJourneyPhaseManager(IJourneyPhaseManager _journeyPhaseManager) public onlyTrustedEntity {
journeyPhaseManager = _journeyPhaseManager;
emit JourneyPhaseManagerSet(_journeyPhaseManager);
}
/// @notice Ends the minting process by setting the claimsContract to the zero address
/// @dev Callable only by the claimsContract
function endMinting() public {
if (msg.sender != claimsContract) revert Unauthorized();
if (totalSupply != MAX_SUPPLY) revert NotYetReachedSupplyLimit();
claimsContract = address(0);
}
/// @notice Updates the trusted entity address
/// @param newTrustedEntity The new address to set as the trusted entity
function updateTrustedEntity(address newTrustedEntity) external onlyTrustedEntity {
if (newTrustedEntity == address(0)) revert TrustedEntityCannotBeEmpty();
emit TrustedEntityUpdated(trustedEntity, newTrustedEntity);
trustedEntity = newTrustedEntity;
}
/// @notice Adds an address to the allowlist
/// @param account The address to add
function addToAllowlist(address account) external onlyTrustedEntity {
if (allowlist[account]) {
revert AlreadyAllowlisted(account);
}
if (account == address(0)) revert AllowlistedAddressCannotBeZero();
allowlist[account] = true;
emit AllowlistAdded(account);
}
/// @notice Removes an address from the allowlist
/// @param account The address to remove
function removeFromAllowlist(address account) external onlyTrustedEntity {
allowlist[account] = false;
emit AllowlistRemoved(account);
}
/// @notice Triggers the rapture
function triggerRapture() external {
// rapture after JourneyPhaseManager activates it
if (!journeyPhaseManager.isRaptureAlertActive()) {
revert CannotRaptureBeforeAlert();
}
if (raptureOccurred) revert AlreadyRaptured();
uint256 newTotalSupply = 0;
address currentHolder = holders[SENTINEL_HOLDERS];
while (currentHolder != SENTINEL_HOLDERS) {
if (allowlist[currentHolder]) {
newTotalSupply += balanceOf[currentHolder]; // Sum whitelisted holders' balances
}
currentHolder = holders[currentHolder];
}
currentHolder = holders[SENTINEL_HOLDERS];
while (currentHolder != SENTINEL_HOLDERS) {
uint256 balance = balanceOf[currentHolder];
// only burn tokens from non whitelisted holders
if (balance > 0 && !allowlist[currentHolder]) {
balanceOf[currentHolder] = 0;
// not updating the total supply because the whole total supply will be updated in the end
emit Transfer(currentHolder, address(0), balance);
}
currentHolder = holders[currentHolder];
}
totalSupply = newTotalSupply;
raptureOccurred = true;
emit RaptureOccurred();
}
/// @dev Overrides the transfer function
/// @param to The address to transfer to
/// @param amount The amount to transfer
function transfer(address to, uint256 amount) public virtual override returns (bool) {
if (!raptureOccurred) _addHolder(to);
return super.transfer(to, amount);
}
/// @dev Overrides the transferFrom function
/// @param from The address to transfer from
/// @param to The address to transfer to
/// @param amount The amount to transfer
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
if (!raptureOccurred) _addHolder(to);
return super.transferFrom(from, to, amount);
}
/// @dev Adds a new holder to the holders
/// @param holder The address of the new holder
function _addHolder(address holder) internal {
// holder address cannot be null, the sentinel.
if (holder == address(0) || holder == SENTINEL_HOLDERS) return;
// No duplicate owners allowed.
if (holders[holder] != address(0)) return;
holders[holder] = holders[SENTINEL_HOLDERS];
holders[SENTINEL_HOLDERS] = holder;
holderCount++;
emit AddedHolder(holder);
}
/// @notice Checks if an address is a holder
/// @param holder The address to check
function isHolder(address holder) public view returns (bool) {
return !(holder == SENTINEL_HOLDERS || holders[holder] == address(0));
}
}
/ERC20.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*//////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*//////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*//////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*//////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
address recoveredAddress = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
/MerkleProofLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Gas optimized verification of proof of inclusion for a leaf in a Merkle tree.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/MerkleProofLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/MerkleProofLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/MerkleProof.sol)
library MerkleProofLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MERKLE PROOF VERIFICATION OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether `leaf` exists in the Merkle tree with `root`, given `proof`.
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf)
internal
pure
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
if mload(proof) {
// Initialize `offset` to the offset of `proof` elements in memory.
let offset := add(proof, 0x20)
// Left shift by 5 is equivalent to multiplying by 0x20.
let end := add(offset, shl(5, mload(proof)))
// Iterate over proof elements to compute root hash.
for {} 1 {} {
// Slot of `leaf` in scratch space.
// If the condition is true: 0x20, otherwise: 0x00.
let scratch := shl(5, gt(leaf, mload(offset)))
// Store elements to hash contiguously in scratch space.
// Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes.
mstore(scratch, leaf)
mstore(xor(scratch, 0x20), mload(offset))
// Reuse `leaf` to store the hash to reduce stack operations.
leaf := keccak256(0x00, 0x40)
offset := add(offset, 0x20)
if iszero(lt(offset, end)) { break }
}
}
isValid := eq(leaf, root)
}
}
/// @dev Returns whether `leaf` exists in the Merkle tree with `root`, given `proof`.
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf)
internal
pure
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
if proof.length {
// Left shift by 5 is equivalent to multiplying by 0x20.
let end := add(proof.offset, shl(5, proof.length))
// Initialize `offset` to the offset of `proof` in the calldata.
let offset := proof.offset
// Iterate over proof elements to compute root hash.
for {} 1 {} {
// Slot of `leaf` in scratch space.
// If the condition is true: 0x20, otherwise: 0x00.
let scratch := shl(5, gt(leaf, calldataload(offset)))
// Store elements to hash contiguously in scratch space.
// Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes.
mstore(scratch, leaf)
mstore(xor(scratch, 0x20), calldataload(offset))
// Reuse `leaf` to store the hash to reduce stack operations.
leaf := keccak256(0x00, 0x40)
offset := add(offset, 0x20)
if iszero(lt(offset, end)) { break }
}
}
isValid := eq(leaf, root)
}
}
/// @dev Returns whether all `leaves` exist in the Merkle tree with `root`,
/// given `proof` and `flags`.
///
/// Note:
/// - Breaking the invariant `flags.length == (leaves.length - 1) + proof.length`
/// will always return false.
/// - The sum of the lengths of `proof` and `leaves` must never overflow.
/// - Any non-zero word in the `flags` array is treated as true.
/// - The memory offset of `proof` must be non-zero
/// (i.e. `proof` is not pointing to the scratch space).
function verifyMultiProof(
bytes32[] memory proof,
bytes32 root,
bytes32[] memory leaves,
bool[] memory flags
) internal pure returns (bool isValid) {
// Rebuilds the root by consuming and producing values on a queue.
// The queue starts with the `leaves` array, and goes into a `hashes` array.
// After the process, the last element on the queue is verified
// to be equal to the `root`.
//
// The `flags` array denotes whether the sibling
// should be popped from the queue (`flag == true`), or
// should be popped from the `proof` (`flag == false`).
/// @solidity memory-safe-assembly
assembly {
// Cache the lengths of the arrays.
let leavesLength := mload(leaves)
let proofLength := mload(proof)
let flagsLength := mload(flags)
// Advance the pointers of the arrays to point to the data.
leaves := add(0x20, leaves)
proof := add(0x20, proof)
flags := add(0x20, flags)
// If the number of flags is correct.
for {} eq(add(leavesLength, proofLength), add(flagsLength, 1)) {} {
// For the case where `proof.length + leaves.length == 1`.
if iszero(flagsLength) {
// `isValid = (proof.length == 1 ? proof[0] : leaves[0]) == root`.
isValid := eq(mload(xor(leaves, mul(xor(proof, leaves), proofLength))), root)
break
}
// The required final proof offset if `flagsLength` is not zero, otherwise zero.
let proofEnd := add(proof, shl(5, proofLength))
// We can use the free memory space for the queue.
// We don't need to allocate, since the queue is temporary.
let hashesFront := mload(0x40)
// Copy the leaves into the hashes.
// Sometimes, a little memory expansion costs less than branching.
// Should cost less, even with a high free memory offset of 0x7d00.
leavesLength := shl(5, leavesLength)
for { let i := 0 } iszero(eq(i, leavesLength)) { i := add(i, 0x20) } {
mstore(add(hashesFront, i), mload(add(leaves, i)))
}
// Compute the back of the hashes.
let hashesBack := add(hashesFront, leavesLength)
// This is the end of the memory for the queue.
// We recycle `flagsLength` to save on stack variables (sometimes save gas).
flagsLength := add(hashesBack, shl(5, flagsLength))
for {} 1 {} {
// Pop from `hashes`.
let a := mload(hashesFront)
// Pop from `hashes`.
let b := mload(add(hashesFront, 0x20))
hashesFront := add(hashesFront, 0x40)
// If the flag is false, load the next proof,
// else, pops from the queue.
if iszero(mload(flags)) {
// Loads the next proof.
b := mload(proof)
proof := add(proof, 0x20)
// Unpop from `hashes`.
hashesFront := sub(hashesFront, 0x20)
}
// Advance to the next flag.
flags := add(flags, 0x20)
// Slot of `a` in scratch space.
// If the condition is true: 0x20, otherwise: 0x00.
let scratch := shl(5, gt(a, b))
// Hash the scratch space and push the result onto the queue.
mstore(scratch, a)
mstore(xor(scratch, 0x20), b)
mstore(hashesBack, keccak256(0x00, 0x40))
hashesBack := add(hashesBack, 0x20)
if iszero(lt(hashesBack, flagsLength)) { break }
}
isValid :=
and(
// Checks if the last value in the queue is same as the root.
eq(mload(sub(hashesBack, 0x20)), root),
// And whether all the proofs are used, if required.
eq(proofEnd, proof)
)
break
}
}
}
/// @dev Returns whether all `leaves` exist in the Merkle tree with `root`,
/// given `proof` and `flags`.
///
/// Note:
/// - Breaking the invariant `flags.length == (leaves.length - 1) + proof.length`
/// will always return false.
/// - Any non-zero word in the `flags` array is treated as true.
/// - The calldata offset of `proof` must be non-zero
/// (i.e. `proof` is from a regular Solidity function with a 4-byte selector).
function verifyMultiProofCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32[] calldata leaves,
bool[] calldata flags
) internal pure returns (bool isValid) {
// Rebuilds the root by consuming and producing values on a queue.
// The queue starts with the `leaves` array, and goes into a `hashes` array.
// After the process, the last element on the queue is verified
// to be equal to the `root`.
//
// The `flags` array denotes whether the sibling
// should be popped from the queue (`flag == true`), or
// should be popped from the `proof` (`flag == false`).
/// @solidity memory-safe-assembly
assembly {
// If the number of flags is correct.
for {} eq(add(leaves.length, proof.length), add(flags.length, 1)) {} {
// For the case where `proof.length + leaves.length == 1`.
if iszero(flags.length) {
// `isValid = (proof.length == 1 ? proof[0] : leaves[0]) == root`.
// forgefmt: disable-next-item
isValid := eq(
calldataload(
xor(leaves.offset, mul(xor(proof.offset, leaves.offset), proof.length))
),
root
)
break
}
// The required final proof offset if `flagsLength` is not zero, otherwise zero.
let proofEnd := add(proof.offset, shl(5, proof.length))
// We can use the free memory space for the queue.
// We don't need to allocate, since the queue is temporary.
let hashesFront := mload(0x40)
// Copy the leaves into the hashes.
// Sometimes, a little memory expansion costs less than branching.
// Should cost less, even with a high free memory offset of 0x7d00.
calldatacopy(hashesFront, leaves.offset, shl(5, leaves.length))
// Compute the back of the hashes.
let hashesBack := add(hashesFront, shl(5, leaves.length))
// This is the end of the memory for the queue.
// We recycle `flagsLength` to save on stack variables (sometimes save gas).
flags.length := add(hashesBack, shl(5, flags.length))
// We don't need to make a copy of `proof.offset` or `flags.offset`,
// as they are pass-by-value (this trick may not always save gas).
for {} 1 {} {
// Pop from `hashes`.
let a := mload(hashesFront)
// Pop from `hashes`.
let b := mload(add(hashesFront, 0x20))
hashesFront := add(hashesFront, 0x40)
// If the flag is false, load the next proof,
// else, pops from the queue.
if iszero(calldataload(flags.offset)) {
// Loads the next proof.
b := calldataload(proof.offset)
proof.offset := add(proof.offset, 0x20)
// Unpop from `hashes`.
hashesFront := sub(hashesFront, 0x20)
}
// Advance to the next flag offset.
flags.offset := add(flags.offset, 0x20)
// Slot of `a` in scratch space.
// If the condition is true: 0x20, otherwise: 0x00.
let scratch := shl(5, gt(a, b))
// Hash the scratch space and push the result onto the queue.
mstore(scratch, a)
mstore(xor(scratch, 0x20), b)
mstore(hashesBack, keccak256(0x00, 0x40))
hashesBack := add(hashesBack, 0x20)
if iszero(lt(hashesBack, flags.length)) { break }
}
isValid :=
and(
// Checks if the last value in the queue is same as the root.
eq(mload(sub(hashesBack, 0x20)), root),
// And whether all the proofs are used, if required.
eq(proofEnd, proof.offset)
)
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EMPTY CALLDATA HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an empty calldata bytes32 array.
function emptyProof() internal pure returns (bytes32[] calldata proof) {
/// @solidity memory-safe-assembly
assembly {
proof.length := 0
}
}
/// @dev Returns an empty calldata bytes32 array.
function emptyLeaves() internal pure returns (bytes32[] calldata leaves) {
/// @solidity memory-safe-assembly
assembly {
leaves.length := 0
}
}
/// @dev Returns an empty calldata bool array.
function emptyFlags() internal pure returns (bool[] calldata flags) {
/// @solidity memory-safe-assembly
assembly {
flags.length := 0
}
}
}
/LibString.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for converting numbers into strings and other string operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
///
/// Note:
/// For performance and bytecode compactness, most of the string operations are restricted to
/// byte strings (7-bit ASCII), except where otherwise specified.
/// Usage of byte string operations on charsets with runes spanning two or more bytes
/// can lead to undefined behavior.
library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The length of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/// @dev The length of the string is more than 32 bytes.
error TooBigForSmallString();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
str := add(mload(0x40), 0x80)
// Update the free memory pointer to allocate.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end of the memory to calculate the length later.
let end := str
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
str := add(str, w) // `sub(str, 1)`.
// Write the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(str, add(48, mod(temp, 10)))
// Keep dividing `temp` until zero.
temp := div(temp, 10)
if iszero(temp) { break }
}
let length := sub(end, str)
// Move the pointer 32 bytes leftwards to make room for the length.
str := sub(str, 0x20)
// Store the length.
mstore(str, length)
}
}
/// @dev Returns the base 10 decimal representation of `value`.
function toString(int256 value) internal pure returns (string memory str) {
if (value >= 0) {
return toString(uint256(value));
}
unchecked {
str = toString(uint256(-value));
}
/// @solidity memory-safe-assembly
assembly {
// We still have some spare memory space on the left,
// as we have allocated 3 words (96 bytes) for up to 78 digits.
let length := mload(str) // Load the string length.
mstore(str, 0x2d) // Store the '-' character.
str := sub(str, 1) // Move back the string pointer by a byte.
mstore(str, add(length, 1)) // Update the string length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HEXADECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `length` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `length * 2 + 2` bytes.
/// Reverts if `length` is too small for the output to contain all the digits.
function toHexString(uint256 value, uint256 length) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value, length);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `length` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `length * 2` bytes.
/// Reverts if `length` is too small for the output to contain all the digits.
function toHexStringNoPrefix(uint256 value, uint256 length)
internal
pure
returns (string memory str)
{
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, `length * 2` bytes
// for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
// We add 0x20 to the total and round down to a multiple of 0x20.
// (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
str := add(mload(0x40), and(add(shl(1, length), 0x42), not(0x1f)))
// Allocate the memory.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end to calculate the length later.
let end := str
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let start := sub(str, add(length, length))
let w := not(1) // Tsk.
let temp := value
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for {} 1 {} {
str := add(str, w) // `sub(str, 2)`.
mstore8(add(str, 1), mload(and(temp, 15)))
mstore8(str, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(xor(str, start)) { break }
}
if temp {
mstore(0x00, 0x2194895a) // `HexLengthInsufficient()`.
revert(0x1c, 0x04)
}
// Compute the string's length.
let strLength := sub(end, str)
// Move the pointer and write the length.
str := sub(str, 0x20)
mstore(str, strLength)
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2 + 2` bytes.
function toHexString(uint256 value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x".
/// The output excludes leading "0" from the `toHexString` output.
/// `0x00: "0x0", 0x01: "0x1", 0x12: "0x12", 0x123: "0x123"`.
function toMinimalHexString(uint256 value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(str, 0x20))), 0x30) // Whether leading zero is present.
let strLength := add(mload(str), 2) // Compute the length.
mstore(add(str, o), 0x3078) // Write the "0x" prefix, accounting for leading zero.
str := sub(add(str, o), 2) // Move the pointer, accounting for leading zero.
mstore(str, sub(strLength, o)) // Write the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output excludes leading "0" from the `toHexStringNoPrefix` output.
/// `0x00: "0", 0x01: "1", 0x12: "12", 0x123: "123"`.
function toMinimalHexStringNoPrefix(uint256 value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(str, 0x20))), 0x30) // Whether leading zero is present.
let strLength := mload(str) // Get the length.
str := add(str, o) // Move the pointer, accounting for leading zero.
mstore(str, sub(strLength, o)) // Write the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2` bytes.
function toHexStringNoPrefix(uint256 value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x40 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
str := add(mload(0x40), 0x80)
// Allocate the memory.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end to calculate the length later.
let end := str
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let w := not(1) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
str := add(str, w) // `sub(str, 2)`.
mstore8(add(str, 1), mload(and(temp, 15)))
mstore8(str, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(temp) { break }
}
// Compute the string's length.
let strLength := sub(end, str)
// Move the pointer and write the length.
str := sub(str, 0x20)
mstore(str, strLength)
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x", encoded using 2 hexadecimal digits per byte,
/// and the alphabets are capitalized conditionally according to
/// https://eips.ethereum.org/EIPS/eip-55
function toHexStringChecksummed(address value) internal pure returns (string memory str) {
str = toHexString(value);
/// @solidity memory-safe-assembly
assembly {
let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`
let o := add(str, 0x22)
let hashed := and(keccak256(o, 40), mul(34, mask)) // `0b10001000 ... `
let t := shl(240, 136) // `0b10001000 << 240`
for { let i := 0 } 1 {} {
mstore(add(i, i), mul(t, byte(i, hashed)))
i := add(i, 1)
if eq(i, 20) { break }
}
mstore(o, xor(mload(o), shr(1, and(mload(0x00), and(mload(o), mask)))))
o := add(o, 0x20)
mstore(o, xor(mload(o), shr(1, and(mload(0x20), and(mload(o), mask)))))
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
function toHexString(address value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(address value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
str := mload(0x40)
// Allocate the memory.
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x28 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x28) is 0x80.
mstore(0x40, add(str, 0x80))
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
str := add(str, 2)
mstore(str, 40)
let o := add(str, 0x20)
mstore(add(o, 40), 0)
value := shl(96, value)
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let i := 0 } 1 {} {
let p := add(o, add(i, i))
let temp := byte(i, value)
mstore8(add(p, 1), mload(and(temp, 15)))
mstore8(p, mload(shr(4, temp)))
i := add(i, 1)
if eq(i, 20) { break }
}
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexString(bytes memory raw) internal pure returns (string memory str) {
str = toHexStringNoPrefix(raw);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(bytes memory raw) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
let length := mload(raw)
str := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.
mstore(str, add(length, length)) // Store the length of the output.
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let o := add(str, 0x20)
let end := add(raw, length)
for {} iszero(eq(raw, end)) {} {
raw := add(raw, 1)
mstore8(add(o, 1), mload(and(mload(raw), 15)))
mstore8(o, mload(and(shr(4, mload(raw)), 15)))
o := add(o, 2)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate the memory.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RUNE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the number of UTF characters in the string.
function runeCount(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
mstore(0x00, div(not(0), 255))
mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506)
let o := add(s, 0x20)
let end := add(o, mload(s))
for { result := 1 } 1 { result := add(result, 1) } {
o := add(o, byte(0, mload(shr(250, mload(o)))))
if iszero(lt(o, end)) { break }
}
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string.
/// (i.e. all characters codes are in [0..127])
function is7BitASCII(string memory s) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
let mask := shl(7, div(not(0), 255))
result := 1
let n := mload(s)
if n {
let o := add(s, 0x20)
let end := add(o, n)
let last := mload(end)
mstore(end, 0)
for {} 1 {} {
if and(mask, mload(o)) {
result := 0
break
}
o := add(o, 0x20)
if iszero(lt(o, end)) { break }
}
mstore(end, last)
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance and bytecode compactness, byte string operations are restricted
// to 7-bit ASCII strings. All offsets are byte offsets, not UTF character offsets.
// Usage of byte string operations on charsets with runes spanning two or more bytes
// can lead to undefined behavior.
/// @dev Returns `subject` all occurrences of `search` replaced with `replacement`.
function replace(string memory subject, string memory search, string memory replacement)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
let searchLength := mload(search)
let replacementLength := mload(replacement)
subject := add(subject, 0x20)
search := add(search, 0x20)
replacement := add(replacement, 0x20)
result := add(mload(0x40), 0x20)
let subjectEnd := add(subject, subjectLength)
if iszero(gt(searchLength, subjectLength)) {
let subjectSearchEnd := add(sub(subjectEnd, searchLength), 1)
let h := 0
if iszero(lt(searchLength, 0x20)) { h := keccak256(search, searchLength) }
let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
let s := mload(search)
for {} 1 {} {
let t := mload(subject)
// Whether the first `searchLength % 32` bytes of
// `subject` and `search` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(subject, searchLength), h)) {
mstore(result, t)
result := add(result, 1)
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
// Copy the `replacement` one word at a time.
for { let o := 0 } 1 {} {
mstore(add(result, o), mload(add(replacement, o)))
o := add(o, 0x20)
if iszero(lt(o, replacementLength)) { break }
}
result := add(result, replacementLength)
subject := add(subject, searchLength)
if searchLength {
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
mstore(result, t)
result := add(result, 1)
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
}
}
let resultRemainder := result
result := add(mload(0x40), 0x20)
let k := add(sub(resultRemainder, result), sub(subjectEnd, subject))
// Copy the rest of the string one word at a time.
for {} lt(subject, subjectEnd) {} {
mstore(resultRemainder, mload(subject))
resultRemainder := add(resultRemainder, 0x20)
subject := add(subject, 0x20)
}
result := sub(result, 0x20)
let last := add(add(result, 0x20), k) // Zeroize the slot after the string.
mstore(last, 0)
mstore(0x40, add(last, 0x20)) // Allocate the memory.
mstore(result, k) // Store the length.
}
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function indexOf(string memory subject, string memory search, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
for { let subjectLength := mload(subject) } 1 {} {
if iszero(mload(search)) {
if iszero(gt(from, subjectLength)) {
result := from
break
}
result := subjectLength
break
}
let searchLength := mload(search)
let subjectStart := add(subject, 0x20)
result := not(0) // Initialize to `NOT_FOUND`.
subject := add(subjectStart, from)
let end := add(sub(add(subjectStart, subjectLength), searchLength), 1)
let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
let s := mload(add(search, 0x20))
if iszero(and(lt(subject, end), lt(from, subjectLength))) { break }
if iszero(lt(searchLength, 0x20)) {
for { let h := keccak256(add(search, 0x20), searchLength) } 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
if eq(keccak256(subject, searchLength), h) {
result := sub(subject, subjectStart)
break
}
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
for {} 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
result := sub(subject, subjectStart)
break
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function indexOf(string memory subject, string memory search)
internal
pure
returns (uint256 result)
{
result = indexOf(subject, search, 0);
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function lastIndexOf(string memory subject, string memory search, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
for {} 1 {} {
result := not(0) // Initialize to `NOT_FOUND`.
let searchLength := mload(search)
if gt(searchLength, mload(subject)) { break }
let w := result
let fromMax := sub(mload(subject), searchLength)
if iszero(gt(fromMax, from)) { from := fromMax }
let end := add(add(subject, 0x20), w)
subject := add(add(subject, 0x20), from)
if iszero(gt(subject, end)) { break }
// As this function is not too often used,
// we shall simply use keccak256 for smaller bytecode size.
for { let h := keccak256(add(search, 0x20), searchLength) } 1 {} {
if eq(keccak256(subject, searchLength), h) {
result := sub(subject, add(end, 1))
break
}
subject := add(subject, w) // `sub(subject, 1)`.
if iszero(gt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function lastIndexOf(string memory subject, string memory search)
internal
pure
returns (uint256 result)
{
result = lastIndexOf(subject, search, uint256(int256(-1)));
}
/// @dev Returns true if `search` is found in `subject`, false otherwise.
function contains(string memory subject, string memory search) internal pure returns (bool) {
return indexOf(subject, search) != NOT_FOUND;
}
/// @dev Returns whether `subject` starts with `search`.
function startsWith(string memory subject, string memory search)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let searchLength := mload(search)
// Just using keccak256 directly is actually cheaper.
// forgefmt: disable-next-item
result := and(
iszero(gt(searchLength, mload(subject))),
eq(
keccak256(add(subject, 0x20), searchLength),
keccak256(add(search, 0x20), searchLength)
)
)
}
}
/// @dev Returns whether `subject` ends with `search`.
function endsWith(string memory subject, string memory search)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let searchLength := mload(search)
let subjectLength := mload(subject)
// Whether `search` is not longer than `subject`.
let withinRange := iszero(gt(searchLength, subjectLength))
// Just using keccak256 directly is actually cheaper.
// forgefmt: disable-next-item
result := and(
withinRange,
eq(
keccak256(
// `subject + 0x20 + max(subjectLength - searchLength, 0)`.
add(add(subject, 0x20), mul(withinRange, sub(subjectLength, searchLength))),
searchLength
),
keccak256(add(search, 0x20), searchLength)
)
)
}
}
/// @dev Returns `subject` repeated `times`.
function repeat(string memory subject, uint256 times)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
if iszero(or(iszero(times), iszero(subjectLength))) {
subject := add(subject, 0x20)
result := mload(0x40)
let output := add(result, 0x20)
for {} 1 {} {
// Copy the `subject` one word at a time.
for { let o := 0 } 1 {} {
mstore(add(output, o), mload(add(subject, o)))
o := add(o, 0x20)
if iszero(lt(o, subjectLength)) { break }
}
output := add(output, subjectLength)
times := sub(times, 1)
if iszero(times) { break }
}
mstore(output, 0) // Zeroize the slot after the string.
let resultLength := sub(output, add(result, 0x20))
mstore(result, resultLength) // Store the length.
// Allocate the memory.
mstore(0x40, add(result, add(resultLength, 0x20)))
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(string memory subject, uint256 start, uint256 end)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
if iszero(gt(subjectLength, end)) { end := subjectLength }
if iszero(gt(subjectLength, start)) { start := subjectLength }
if lt(start, end) {
result := mload(0x40)
let resultLength := sub(end, start)
mstore(result, resultLength)
subject := add(subject, start)
let w := not(0x1f)
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(resultLength, 0x1f), w) } 1 {} {
mstore(add(result, o), mload(add(subject, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
// Zeroize the slot after the string.
mstore(add(add(result, 0x20), resultLength), 0)
// Allocate memory for the length and the bytes,
// rounded up to a multiple of 32.
mstore(0x40, add(result, and(add(resultLength, 0x3f), w)))
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the string.
/// `start` is a byte offset.
function slice(string memory subject, uint256 start)
internal
pure
returns (string memory result)
{
result = slice(subject, start, uint256(int256(-1)));
}
/// @dev Returns all the indices of `search` in `subject`.
/// The indices are byte offsets.
function indicesOf(string memory subject, string memory search)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
let searchLength := mload(search)
if iszero(gt(searchLength, subjectLength)) {
subject := add(subject, 0x20)
search := add(search, 0x20)
result := add(mload(0x40), 0x20)
let subjectStart := subject
let subjectSearchEnd := add(sub(add(subject, subjectLength), searchLength), 1)
let h := 0
if iszero(lt(searchLength, 0x20)) { h := keccak256(search, searchLength) }
let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
let s := mload(search)
for {} 1 {} {
let t := mload(subject)
// Whether the first `searchLength % 32` bytes of
// `subject` and `search` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(subject, searchLength), h)) {
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
// Append to `result`.
mstore(result, sub(subject, subjectStart))
result := add(result, 0x20)
// Advance `subject` by `searchLength`.
subject := add(subject, searchLength)
if searchLength {
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
}
let resultEnd := result
// Assign `result` to the free memory pointer.
result := mload(0x40)
// Store the length of `result`.
mstore(result, shr(5, sub(resultEnd, add(result, 0x20))))
// Allocate memory for result.
// We allocate one more word, so this array can be recycled for {split}.
mstore(0x40, add(resultEnd, 0x20))
}
}
}
/// @dev Returns a arrays of strings based on the `delimiter` inside of the `subject` string.
function split(string memory subject, string memory delimiter)
internal
pure
returns (string[] memory result)
{
uint256[] memory indices = indicesOf(subject, delimiter);
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
let indexPtr := add(indices, 0x20)
let indicesEnd := add(indexPtr, shl(5, add(mload(indices), 1)))
mstore(add(indicesEnd, w), mload(subject))
mstore(indices, add(mload(indices), 1))
let prevIndex := 0
for {} 1 {} {
let index := mload(indexPtr)
mstore(indexPtr, 0x60)
if iszero(eq(index, prevIndex)) {
let element := mload(0x40)
let elementLength := sub(index, prevIndex)
mstore(element, elementLength)
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(elementLength, 0x1f), w) } 1 {} {
mstore(add(element, o), mload(add(add(subject, prevIndex), o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
// Zeroize the slot after the string.
mstore(add(add(element, 0x20), elementLength), 0)
// Allocate memory for the length and the bytes,
// rounded up to a multiple of 32.
mstore(0x40, add(element, and(add(elementLength, 0x3f), w)))
// Store the `element` into the array.
mstore(indexPtr, element)
}
prevIndex := add(index, mload(delimiter))
indexPtr := add(indexPtr, 0x20)
if iszero(lt(indexPtr, indicesEnd)) { break }
}
result := indices
if iszero(mload(delimiter)) {
result := add(indices, 0x20)
mstore(result, sub(mload(indices), 2))
}
}
}
/// @dev Returns a concatenated string of `a` and `b`.
/// Cheaper than `string.concat()` and does not de-align the free memory pointer.
function concat(string memory a, string memory b)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
result := mload(0x40)
let aLength := mload(a)
// Copy `a` one word at a time, backwards.
for { let o := and(add(aLength, 0x20), w) } 1 {} {
mstore(add(result, o), mload(add(a, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let bLength := mload(b)
let output := add(result, aLength)
// Copy `b` one word at a time, backwards.
for { let o := and(add(bLength, 0x20), w) } 1 {} {
mstore(add(output, o), mload(add(b, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let totalLength := add(aLength, bLength)
let last := add(add(result, 0x20), totalLength)
// Zeroize the slot after the string.
mstore(last, 0)
// Stores the length.
mstore(result, totalLength)
// Allocate memory for the length and the bytes,
// rounded up to a multiple of 32.
mstore(0x40, and(add(last, 0x1f), w))
}
}
/// @dev Returns a copy of the string in either lowercase or UPPERCASE.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function toCase(string memory subject, bool toUpper)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let length := mload(subject)
if length {
result := add(mload(0x40), 0x20)
subject := add(subject, 1)
let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
let w := not(0)
for { let o := length } 1 {} {
o := add(o, w)
let b := and(0xff, mload(add(subject, o)))
mstore8(add(result, o), xor(b, and(shr(b, flags), 0x20)))
if iszero(o) { break }
}
result := mload(0x40)
mstore(result, length) // Store the length.
let last := add(add(result, 0x20), length)
mstore(last, 0) // Zeroize the slot after the string.
mstore(0x40, add(last, 0x20)) // Allocate the memory.
}
}
}
/// @dev Returns a string from a small bytes32 string.
/// `s` must be null-terminated, or behavior will be undefined.
function fromSmallString(bytes32 s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let n := 0
for {} byte(n, s) { n := add(n, 1) } {} // Scan for '\0'.
mstore(result, n)
let o := add(result, 0x20)
mstore(o, s)
mstore(add(o, n), 0)
mstore(0x40, add(result, 0x40))
}
}
/// @dev Returns the small string, with all bytes after the first null byte zeroized.
function normalizeSmallString(bytes32 s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
for {} byte(result, s) { result := add(result, 1) } {} // Scan for '\0'.
mstore(0x00, s)
mstore(result, 0x00)
result := mload(0x00)
}
}
/// @dev Returns the string as a normalized null-terminated small string.
function toSmallString(string memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(s)
if iszero(lt(result, 33)) {
mstore(0x00, 0xec92f9a3) // `TooBigForSmallString()`.
revert(0x1c, 0x04)
}
result := shl(shl(3, sub(32, result)), mload(add(s, result)))
}
}
/// @dev Returns a lowercased copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function lower(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, false);
}
/// @dev Returns an UPPERCASED copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function upper(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, true);
}
/// @dev Escapes the string to be used within HTML tags.
function escapeHTML(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
let end := add(s, mload(s))
result := add(mload(0x40), 0x20)
// Store the bytes of the packed offsets and strides into the scratch space.
// `packed = (stride << 5) | offset`. Max offset is 20. Max stride is 6.
mstore(0x1f, 0x900094)
mstore(0x08, 0xc0000000a6ab)
// Store ""&'<>" into the scratch space.
mstore(0x00, shl(64, 0x2671756f743b26616d703b262333393b266c743b2667743b))
for {} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// Not in `["\"","'","&","<",">"]`.
if iszero(and(shl(c, 1), 0x500000c400000000)) {
mstore8(result, c)
result := add(result, 1)
continue
}
let t := shr(248, mload(c))
mstore(result, mload(and(t, 0x1f)))
result := add(result, shr(5, t))
}
let last := result
mstore(last, 0) // Zeroize the slot after the string.
result := mload(0x40)
mstore(result, sub(last, add(result, 0x20))) // Store the length.
mstore(0x40, add(last, 0x20)) // Allocate the memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
/// If `addDoubleQuotes` is true, the result will be enclosed in double-quotes.
function escapeJSON(string memory s, bool addDoubleQuotes)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let end := add(s, mload(s))
result := add(mload(0x40), 0x20)
if addDoubleQuotes {
mstore8(result, 34)
result := add(1, result)
}
// Store "\\u0000" in scratch space.
// Store "0123456789abcdef" in scratch space.
// Also, store `{0x08:"b", 0x09:"t", 0x0a:"n", 0x0c:"f", 0x0d:"r"}`.
// into the scratch space.
mstore(0x15, 0x5c75303030303031323334353637383961626364656662746e006672)
// Bitmask for detecting `["\"","\\"]`.
let e := or(shl(0x22, 1), shl(0x5c, 1))
for {} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
if iszero(lt(c, 0x20)) {
if iszero(and(shl(c, 1), e)) {
// Not in `["\"","\\"]`.
mstore8(result, c)
result := add(result, 1)
continue
}
mstore8(result, 0x5c) // "\\".
mstore8(add(result, 1), c)
result := add(result, 2)
continue
}
if iszero(and(shl(c, 1), 0x3700)) {
// Not in `["\b","\t","\n","\f","\d"]`.
mstore8(0x1d, mload(shr(4, c))) // Hex value.
mstore8(0x1e, mload(and(c, 15))) // Hex value.
mstore(result, mload(0x19)) // "\\u00XX".
result := add(result, 6)
continue
}
mstore8(result, 0x5c) // "\\".
mstore8(add(result, 1), mload(add(c, 8)))
result := add(result, 2)
}
if addDoubleQuotes {
mstore8(result, 34)
result := add(1, result)
}
let last := result
mstore(last, 0) // Zeroize the slot after the string.
result := mload(0x40)
mstore(result, sub(last, add(result, 0x20))) // Store the length.
mstore(0x40, add(last, 0x20)) // Allocate the memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
function escapeJSON(string memory s) internal pure returns (string memory result) {
result = escapeJSON(s, false);
}
/// @dev Returns whether `a` equals `b`.
function eq(string memory a, string memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small string.
function eqs(string memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Packs a single string with its length into a single word.
/// Returns `bytes32(0)` if the length is zero or greater than 31.
function packOne(string memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
// We don't need to zero right pad the string,
// since this is our own custom non-standard packing scheme.
result :=
mul(
// Load the length and the bytes.
mload(add(a, 0x1f)),
// `length != 0 && length < 32`. Abuses underflow.
// Assumes that the length is valid and within the block gas limit.
lt(sub(mload(a), 1), 0x1f)
)
}
}
/// @dev Unpacks a string packed using {packOne}.
/// Returns the empty string if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packOne}, the output behavior is undefined.
function unpackOne(bytes32 packed) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// Grab the free memory pointer.
result := mload(0x40)
// Allocate 2 words (1 for the length, 1 for the bytes).
mstore(0x40, add(result, 0x40))
// Zeroize the length slot.
mstore(result, 0)
// Store the length and bytes.
mstore(add(result, 0x1f), packed)
// Right pad with zeroes.
mstore(add(add(result, 0x20), mload(result)), 0)
}
}
/// @dev Packs two strings with their lengths into a single word.
/// Returns `bytes32(0)` if combined length is zero or greater than 30.
function packTwo(string memory a, string memory b) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let aLength := mload(a)
// We don't need to zero right pad the strings,
// since this is our own custom non-standard packing scheme.
result :=
mul(
// Load the length and the bytes of `a` and `b`.
or(
shl(shl(3, sub(0x1f, aLength)), mload(add(a, aLength))),
mload(sub(add(b, 0x1e), aLength))
),
// `totalLength != 0 && totalLength < 31`. Abuses underflow.
// Assumes that the lengths are valid and within the block gas limit.
lt(sub(add(aLength, mload(b)), 1), 0x1e)
)
}
}
/// @dev Unpacks strings packed using {packTwo}.
/// Returns the empty strings if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packTwo}, the output behavior is undefined.
function unpackTwo(bytes32 packed)
internal
pure
returns (string memory resultA, string memory resultB)
{
/// @solidity memory-safe-assembly
assembly {
// Grab the free memory pointer.
resultA := mload(0x40)
resultB := add(resultA, 0x40)
// Allocate 2 words for each string (1 for the length, 1 for the byte). Total 4 words.
mstore(0x40, add(resultB, 0x40))
// Zeroize the length slots.
mstore(resultA, 0)
mstore(resultB, 0)
// Store the lengths and bytes.
mstore(add(resultA, 0x1f), packed)
mstore(add(resultB, 0x1f), mload(add(add(resultA, 0x20), mload(resultA))))
// Right pad with zeroes.
mstore(add(add(resultA, 0x20), mload(resultA)), 0)
mstore(add(add(resultB, 0x20), mload(resultB)), 0)
}
}
/// @dev Directly returns `a` without copying.
function directReturn(string memory a) internal pure {
assembly {
// Assumes that the string does not start from the scratch space.
let retStart := sub(a, 0x20)
let retSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the string is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retSize), 0)
// Store the return offset.
mstore(retStart, 0x20)
// End the transaction, returning the string.
return(retStart, retSize)
}
}
}
/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822.sol";
import "../ERC1967/ERC1967Upgrade.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is IERC1822Proxiable, ERC1967Upgrade {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeTo(address newImplementation) public virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
}
/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
/ERC1967/ERC1967Upgrade.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../interfaces/IERC1967.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*/
abstract contract ERC1967Upgrade is IERC1967 {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*
* _Available since v4.8.3._
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
/math/SignedMathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMathUpgradeable {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
/math/MathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
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;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
/StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.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;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, MathUpgradeable.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
/ERC721/extensions/IERC721MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/ERC721/IERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
/ERC721/IERC721ReceiverUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/ERC721/ERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: address zero is not a valid owner");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _ownerOf(tokenId);
require(owner != address(0), "ERC721: invalid token ID");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
_requireMinted(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not token owner or approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
_requireMinted(tokenId);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_safeTransfer(from, to, tokenId, data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*/
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
return _owners[tokenId];
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _ownerOf(tokenId) != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId, 1);
// Check that tokenId was not minted by `_beforeTokenTransfer` hook
require(!_exists(tokenId), "ERC721: token already minted");
unchecked {
// Will not overflow unless all 2**256 token ids are minted to the same owner.
// Given that tokens are minted one by one, it is impossible in practice that
// this ever happens. Might change if we allow batch minting.
// The ERC fails to describe this case.
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId, 1);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId, 1);
// Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
owner = ERC721Upgradeable.ownerOf(tokenId);
// Clear approvals
delete _tokenApprovals[tokenId];
unchecked {
// Cannot overflow, as that would require more tokens to be burned/transferred
// out than the owner initially received through minting and transferring in.
_balances[owner] -= 1;
}
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId, 1);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId, 1);
// Check that tokenId was not transferred by `_beforeTokenTransfer` hook
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
// Clear approvals from the previous owner
delete _tokenApprovals[tokenId];
unchecked {
// `_balances[from]` cannot overflow for the same reason as described in `_burn`:
// `from`'s balance is the number of token held, which is at least one before the current
// transfer.
// `_balances[to]` could overflow in the conditions described in `_mint`. That would require
// all 2**256 token ids to be minted, which in practice is impossible.
_balances[from] -= 1;
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` has not been minted yet.
*/
function _requireMinted(uint256 tokenId) internal view virtual {
require(_exists(tokenId), "ERC721: invalid token ID");
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
/// @solidity memory-safe-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
* - When `from` is zero, the tokens will be minted for `to`.
* - When `to` is zero, ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}
/**
* @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
* - When `from` is zero, the tokens were minted for `to`.
* - When `to` is zero, ``from``'s tokens were burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
* being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
* that `ownerOf(tokenId)` is `a`.
*/
// solhint-disable-next-line func-name-mixedcase
function __unsafe_increaseBalance(address account, uint256 amount) internal {
_balances[account] += amount;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[44] private __gap;
}
/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
/Ownable2StepUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.0;
import "./OwnableUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
function __Ownable2Step_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable2Step_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
_transferOwnership(sender);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
Compiler Settings
{"remappings":[":@chainlink/=lib/chainlink/",":@era1/=src/ERA1/",":@era2/=src/ERA2/",":@era3/=src/ERA3/",":@erc721a-upgradeable/contracts/=lib/ERC721A-Upgradeable/contracts/",":@erc721a/contracts/=lib/ERC721A/contracts/",":@interfaces/=src/interfaces/",":@mocks/=src/mocks/",":@murky/=lib/murky/",":@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",":@safe/smart-wallet/=lib/safe-smart-account/",":@solady/=lib/solady/",":@solmate/=lib/solmate/",":@uniswap/v2-periphery/=lib/v2-periphery/",":ERC721A-Upgradeable/=lib/ERC721A-Upgradeable/contracts/",":ERC721A/=lib/ERC721A/contracts/",":chainlink/=lib/chainlink/",":ds-test/=lib/forge-std/lib/ds-test/src/",":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",":erc721a/=lib/erc721a/contracts/",":forge-std/=lib/forge-std/src/",":murky/=lib/murky/",":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",":openzeppelin-contracts/=lib/openzeppelin-contracts/",":openzeppelin/=lib/openzeppelin-contracts-upgradeable/contracts/",":safe-smart-account/=lib/safe-smart-account/",":solady/=lib/solady/",":solmate/=lib/solmate/src/",":v2-periphery/=lib/v2-periphery/contracts/"],"optimizer":{"runs":200,"enabled":true},"metadata":{"bytecodeHash":"ipfs"},"libraries":{},"evmVersion":"paris","compilationTarget":{"src/ERA3/Jackpot/Jackpot.sol":"Jackpot"}}
Contract ABI
[{"type":"constructor","stateMutability":"nonpayable","inputs":[]},{"type":"error","name":"AllLotteryConducted","inputs":[]},{"type":"error","name":"AlreadyClaimed","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256"},{"type":"uint16","name":"journeyId","internalType":"uint16"}]},{"type":"error","name":"ArrayLengthMismatch","inputs":[]},{"type":"error","name":"CanPruneForSameAddressOnly","inputs":[]},{"type":"error","name":"CannotRolloverEmptyBonus","inputs":[]},{"type":"error","name":"EmptyRoot","inputs":[]},{"type":"error","name":"EmptyUri","inputs":[]},{"type":"error","name":"JourneyInFuture","inputs":[{"type":"uint16","name":"journeyId","internalType":"uint16"},{"type":"uint16","name":"currentJourneyId","internalType":"uint16"}]},{"type":"error","name":"LotteryAlreadyConducted","inputs":[{"type":"uint16","name":"journeyId","internalType":"uint16"},{"type":"uint16","name":"lotteryId","internalType":"uint16"}]},{"type":"error","name":"LotteryForZeroJourney","inputs":[]},{"type":"error","name":"LotteryForZeroLotteryId","inputs":[]},{"type":"error","name":"LotteryNonSequential","inputs":[{"type":"uint16","name":"lotteryId","internalType":"uint16"},{"type":"uint16","name":"nextLotteryId","internalType":"uint16"}]},{"type":"error","name":"LotteryPhaseNotActive","inputs":[{"type":"uint16","name":"lotteryId","internalType":"uint16"},{"type":"uint256","name":"currentPhase","internalType":"uint256"}]},{"type":"error","name":"NotAWinner","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256"},{"type":"uint16","name":"journeyId","internalType":"uint16"},{"type":"uint16","name":"lotteryId","internalType":"uint16"}]},{"type":"error","name":"PayoutGreaterThanBalance","inputs":[{"type":"uint256","name":"expectedLotteryPayout","internalType":"uint256"},{"type":"uint256","name":"jackpotAvailableBalance","internalType":"uint256"}]},{"type":"error","name":"UnauthorizedKeeper","inputs":[{"type":"address","name":"unknownKeeper","internalType":"address"}]},{"type":"error","name":"WaitForCurrentJourneyBonusToBeUsed","inputs":[]},{"type":"error","name":"ZeroBonusNotAllowed","inputs":[]},{"type":"error","name":"ZeroKeeperAddress","inputs":[]},{"type":"error","name":"ZeroWinnersForLottery","inputs":[{"type":"uint16","name":"journeyId","internalType":"uint16"},{"type":"uint16","name":"lotteryId","internalType":"uint16"}]},{"type":"event","name":"AdminChanged","inputs":[{"type":"address","name":"previousAdmin","internalType":"address","indexed":false},{"type":"address","name":"newAdmin","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"BeaconUpgraded","inputs":[{"type":"address","name":"beacon","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"BonusAdded","inputs":[{"type":"address","name":"sender","internalType":"address","indexed":true},{"type":"uint256","name":"bonusAmount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Initialized","inputs":[{"type":"uint8","name":"version","internalType":"uint8","indexed":false}],"anonymous":false},{"type":"event","name":"KeeperUpdated","inputs":[{"type":"address","name":"newKeeper","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"LotterResultAnnounced","inputs":[{"type":"uint16","name":"journey","internalType":"uint16","indexed":true},{"type":"uint16","name":"lottery","internalType":"uint16","indexed":true},{"type":"uint256","name":"numberOfWinners","internalType":"uint256","indexed":false},{"type":"uint256","name":"payout","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"OwnershipTransferStarted","inputs":[{"type":"address","name":"previousOwner","internalType":"address","indexed":true},{"type":"address","name":"newOwner","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"OwnershipTransferred","inputs":[{"type":"address","name":"previousOwner","internalType":"address","indexed":true},{"type":"address","name":"newOwner","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"Upgraded","inputs":[{"type":"address","name":"implementation","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"WinningPruned","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256","indexed":true},{"type":"uint16","name":"journeyId","internalType":"uint16","indexed":false},{"type":"uint16","name":"lotteryId","internalType":"uint16","indexed":false},{"type":"uint256","name":"winningAmount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"uint16","name":"","internalType":"uint16"}],"name":"BASIS_POINTS","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"FUEL_CELL_PRICE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"HUNDRED_PERCENT","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"JOURNEY_1_DURATION","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"JOURNEY_1_PHASE_1_DURATION","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"JOURNEY_DURATION","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"JOURNEY_PHASE_1","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"JOURNEY_PHASE_2","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"JOURNEY_PHASE_3","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"LOTTERIES_PER_JOURNEY","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"LOTTERY_1_PAYOUT_PERCENTAGE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"LOTTERY_2_PAYOUT_PERCENTAGE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"LOTTERY_3_PAYOUT_PERCENTAGE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"PHASE_1_DURATION","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"PHASE_2_DURATION","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"PHASE_3_DURATION","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"TOTAL_JOURNEYS","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"acceptOwnership","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"announceLotteryResult","inputs":[{"type":"tuple","name":"_result","internalType":"struct JackpotStorage.LotteryResult","components":[{"type":"uint16","name":"journeyId","internalType":"uint16"},{"type":"uint16","name":"lotteryId","internalType":"uint16"},{"type":"uint256","name":"numberOfWinners","internalType":"uint256"},{"type":"bytes32","name":"root","internalType":"bytes32"},{"type":"string","name":"uri","internalType":"string"}]}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"bonus","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint16","name":"currentLotteryId","internalType":"uint16"}],"name":"currentLotteryId","inputs":[{"type":"uint16","name":"journeyId","internalType":"uint16"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract Dark"}],"name":"darkToken","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"depositBonus","inputs":[{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract FuelCell"}],"name":"fuelCellsToken","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"initialize","inputs":[{"type":"address","name":"_darkToken","internalType":"contract Dark"},{"type":"address","name":"_fuelCellsToken","internalType":"contract FuelCell"},{"type":"address","name":"_jpm","internalType":"contract JourneyPhaseManager"},{"type":"address","name":"_keeper","internalType":"address"},{"type":"address","name":"_initialOwner","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isClaimed","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isWinner","inputs":[{"type":"tuple","name":"winning","internalType":"struct JackpotStorage.PruneWinning","components":[{"type":"uint16","name":"journeyId","internalType":"uint16"},{"type":"uint16","name":"lotteryId","internalType":"uint16"},{"type":"uint256","name":"tokenId","internalType":"uint256"},{"type":"bytes32[]","name":"proofs","internalType":"bytes32[]"}]}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract JourneyPhaseManager"}],"name":"jpm","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"keeper","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"numberOfWinners","internalType":"uint256"},{"type":"bytes32","name":"root","internalType":"bytes32"},{"type":"string","name":"uri","internalType":"string"},{"type":"uint256","name":"payoutAmount","internalType":"uint256"}],"name":"lotteryPayouts","inputs":[{"type":"uint16","name":"journeyId","internalType":"uint16"},{"type":"uint16","name":"lotteryId","internalType":"uint16"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"owner","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"pendingOwner","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"proxiableUUID","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"pruneWinnings","inputs":[{"type":"tuple[]","name":"_winnings","internalType":"struct JackpotStorage.PruneWinning[]","components":[{"type":"uint16","name":"journeyId","internalType":"uint16"},{"type":"uint16","name":"lotteryId","internalType":"uint16"},{"type":"uint256","name":"tokenId","internalType":"uint256"},{"type":"bytes32[]","name":"proofs","internalType":"bytes32[]"}]}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"renounceOwnership","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setKeeper","inputs":[{"type":"address","name":"_keeper","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalPendingPayout","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"transferOwnership","inputs":[{"type":"address","name":"newOwner","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"upgradeTo","inputs":[{"type":"address","name":"newImplementation","internalType":"address"}]},{"type":"function","stateMutability":"payable","outputs":[],"name":"upgradeToAndCall","inputs":[{"type":"address","name":"newImplementation","internalType":"address"},{"type":"bytes","name":"data","internalType":"bytes"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"yieldFormulaA","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"yieldFormulaR","inputs":[]}]
Contract Creation Code
0x60a0604052306080523480156200001557600080fd5b506200002062000026565b620000e7565b600054610100900460ff1615620000935760405162461bcd60e51b815260206004820152602760248201527f496e697469616c697a61626c653a20636f6e747261637420697320696e697469604482015266616c697a696e6760c81b606482015260840160405180910390fd5b60005460ff90811614620000e5576000805460ff191660ff9081179091556040519081527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b565b608051612ba16200011f60003960008181610887015281816108c701528181610966015281816109a60152610a430152612ba16000f3fe6080604052600436106102515760003560e01c8063715018a611610139578063bbbd732e116100b6578063e0fcf93d1161007a578063e0fcf93d14610667578063e1f1c4a714610687578063e30c39781461069d578063e93fd958146106bb578063f2fde38b146106d2578063f8d67a2b146106f257600080fd5b8063bbbd732e146105cb578063c41f66f4146105e0578063ce4d7bc414610610578063ce7c2fb914610627578063cf1814bc1461064757600080fd5b8063938ece89116100fd578063938ece89146105215780639cddc9cf146105385780639e34070f14610554578063a89de24914610594578063aced1661146105ab57600080fd5b8063715018a6146104a3578063748747e6146104b857806375b4d78c146104d857806379ba5097146104ee5780638da5cb5b1461050357600080fd5b80632acfc2ca116101d25780634f1ef286116101965780634f1ef286146104175780634fc2fd041461042a57806352d1902d1461044a5780635539aa861461045f5780636839c1bd146104755780636ed93dd01461048c57600080fd5b80632acfc2ca146103a05780632bc477281461038b5780633659cfe6146103c05780633a9f6b74146103e05780634ed718bf1461040057600080fd5b806314b5b43f1161021957806314b5b43f1461030357806318b353101461031a5780632327789a1461033157806324679c3f146103755780632aad34031461038b57600080fd5b806301dd036c1461025657806304ed00ac146102935780630cff04cd146102b75780630f6110c3146102cc5780631459457a146102e1575b600080fd5b34801561026257600080fd5b5060ca54610276906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b34801561029f57600080fd5b506102a960cd5481565b60405190815260200161028a565b3480156102c357600080fd5b506102a9605a81565b3480156102d857600080fd5b506102a9600281565b3480156102ed57600080fd5b506103016102fc3660046123cc565b610707565b005b34801561030f57600080fd5b506102a9620493e081565b34801561032657600080fd5b506102a9620186a081565b34801561033d57600080fd5b5061036261034c366004612454565b60d06020526000908152604090205461ffff1681565b60405161ffff909116815260200161028a565b34801561038157600080fd5b506102a961753081565b34801561039757600080fd5b506102a9600381565b3480156103ac57600080fd5b5060c954610276906001600160a01b031681565b3480156103cc57600080fd5b506103016103db36600461246f565b61087d565b3480156103ec57600080fd5b5060cb54610276906001600160a01b031681565b34801561040c57600080fd5b506102a96215180081565b6103016104253660046124a2565b61095c565b34801561043657600080fd5b50610301610445366004612566565b610a2c565b34801561045657600080fd5b506102a9610a36565b34801561046b57600080fd5b506102a961a8c081565b34801561048157600080fd5b506102a9620e808081565b34801561049857600080fd5b506102a9620f424081565b3480156104af57600080fd5b50610301610ae9565b3480156104c457600080fd5b506103016104d336600461246f565b610afd565b3480156104e457600080fd5b506102a960ce5481565b3480156104fa57600080fd5b50610301610b80565b34801561050f57600080fd5b506033546001600160a01b0316610276565b34801561052d57600080fd5b506102a9622c2a4081565b34801561054457600080fd5b506102a9670de0b6b3a764000081565b34801561056057600080fd5b5061058461056f3660046125db565b60cf6020526000908152604090205460ff1681565b604051901515815260200161028a565b3480156105a057600080fd5b506102a9623b538081565b3480156105b757600080fd5b5060cc54610276906001600160a01b031681565b3480156105d757600080fd5b506102a9602181565b3480156105ec57600080fd5b506106006105fb3660046125f4565b610bf7565b60405161028a9493929190612677565b34801561061c57600080fd5b506102a9620927c081565b34801561063357600080fd5b506105846106423660046126a7565b610cb3565b34801561065357600080fd5b506103016106623660046125db565b610da1565b34801561067357600080fd5b506103016106823660046126e2565b610e8d565b34801561069357600080fd5b5061036261271081565b3480156106a957600080fd5b506065546001600160a01b0316610276565b3480156106c757600080fd5b506102a96241eb0081565b3480156106de57600080fd5b506103016106ed36600461246f565b61166a565b3480156106fe57600080fd5b506102a9600181565b600054610100900460ff16158080156107275750600054600160ff909116105b806107415750303b158015610741575060005460ff166001145b6107a95760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084015b60405180910390fd5b6000805460ff1916600117905580156107cc576000805461ff0019166101001790555b6107d46116db565b6107dc61170a565b6107e582611739565b60c980546001600160a01b038089166001600160a01b03199283161790925560ca805488841690831617905560cb805487841690831617905560cc8054928616929091169190911790558015610875576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050505050565b6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001630036108c55760405162461bcd60e51b81526004016107a09061271d565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031661090e600080516020612b25833981519152546001600160a01b031690565b6001600160a01b0316146109345760405162461bcd60e51b81526004016107a090612769565b61093d81611752565b604080516000808252602082019092526109599183919061175a565b50565b6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001630036109a45760405162461bcd60e51b81526004016107a09061271d565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166109ed600080516020612b25833981519152546001600160a01b031690565b6001600160a01b031614610a135760405162461bcd60e51b81526004016107a090612769565b610a1c82611752565b610a288282600161175a565b5050565b610a2882826118ca565b6000306001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614610ad65760405162461bcd60e51b815260206004820152603860248201527f555550535570677261646561626c653a206d757374206e6f742062652063616c60448201527f6c6564207468726f7567682064656c656761746563616c6c000000000000000060648201526084016107a0565b50600080516020612b2583398151915290565b610af1611e27565b610afb6000611739565b565b610b05611e27565b6001600160a01b038116610b2c5760405163c941d9fb60e01b815260040160405180910390fd5b60cc80546001600160a01b0319166001600160a01b0383169081179091556040519081527f0425bcd291db1d48816f2a98edc7ecaf6dd5c64b973d9e4b3b6b750763dc6c2e9060200160405180910390a150565b60655433906001600160a01b03168114610bee5760405162461bcd60e51b815260206004820152602960248201527f4f776e61626c6532537465703a2063616c6c6572206973206e6f7420746865206044820152683732bb9037bbb732b960b91b60648201526084016107a0565b61095981611739565b60d160209081526000928352604080842090915290825290208054600182015460028301805492939192610c2a906127b5565b80601f0160208091040260200160405190810160405280929190818152602001828054610c56906127b5565b8015610ca35780601f10610c7857610100808354040283529160200191610ca3565b820191906000526020600020905b815481529060010190602001808311610c8657829003601f168201915b5050505050908060030154905084565b6000806040830135610cc86020850185612454565b610cd86040860160208701612454565b604051602001610d0c9392919092835260f091821b6001600160f01b03199081166020850152911b16602282015260240190565b604051602081830303815290604052805190602001209050600060d16000856000016020810190610d3d9190612454565b61ffff1661ffff1681526020019081526020016000206000856020016020810190610d689190612454565b61ffff1681526020810191909152604001600020600101549050610d99610d9260608601866127ef565b8385611e81565b949350505050565b80600003610dc2576040516326d23b5b60e01b815260040160405180910390fd5b8060ce6000828254610dd49190612856565b909155505060c9546040516323b872dd60e01b8152336004820152306024820152604481018390526001600160a01b03909116906323b872dd906064016020604051808303816000875af1158015610e30573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e549190612869565b5060405181815233907f9222d6d887c327442b8c6a5b3731cda3e11f9b1444cd14830bf136a2fb300fae9060200160405180910390a250565b60cc546001600160a01b03163314610eba5760405163c0fe76eb60e01b81523360048201526024016107a0565b610ec2611ebb565b610ecf6020820182612454565b61ffff16600003610ef35760405163670fe71760e01b815260040160405180910390fd5b610f036040820160208301612454565b61ffff16600003610f27576040516305c87e5560e21b815260040160405180910390fd5b6060810135610f49576040516329e7276760e11b815260040160405180910390fd5b8060400135600003610f9957610f626020820182612454565b610f726040830160208401612454565b604051636befa94f60e11b815261ffff9283166004820152911660248201526044016107a0565b600360d06000610fac6020850185612454565b61ffff90811682526020820192909252604001600020541603610fe25760405163602262d960e11b815260040160405180910390fd5b60d16000610ff36020840184612454565b61ffff1661ffff168152602001908152602001600020600082602001602081019061101e9190612454565b61ffff1681526020810191909152604001600020541561107c576110456020820182612454565b6110556040830160208401612454565b604051637279cd0360e01b815261ffff9283166004820152911660248201526044016107a0565b61108c6040820160208301612454565b61ffff1660d060006110a16020850185612454565b61ffff90811682526020820192909252604001600020546110c49116600161288b565b61ffff1614611138576110dd6040820160208301612454565b60d060006110ee6020850185612454565b61ffff90811682526020820192909252604001600020546111119116600161288b565b60405163555ec34560e11b815261ffff9283166004820152911660248201526044016107a0565b60ce54600160d0600061114e6020860186612454565b61ffff908116825260208201929092526040016000908120805490926111769185911661288b565b92506101000a81548161ffff021916908361ffff1602179055508160000160208101906111a39190612454565b61ffff1660cb60009054906101000a90046001600160a01b03166001600160a01b031663be5887456040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111fa573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061121e91906128ad565b10156112cf576112316020830183612454565b60cb60009054906101000a90046001600160a01b03166001600160a01b031663be5887456040518163ffffffff1660e01b8152600401602060405180830381865afa158015611284573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112a891906128ad565b604051631b0295a360e01b815261ffff9283166004820152911660248201526044016107a0565b60cb54604080516302ad6a1760e11b815290516001926001600160a01b03169163055ad42e9160048083019260209291908290030181865afa158015611319573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061133d91906128ad565b036113f0576113526040830160208401612454565b60cb60009054906101000a90046001600160a01b03166001600160a01b031663055ad42e6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156113a5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113c991906128ad565b604051630799a54b60e31b815261ffff9283166004820152911660248201526044016107a0565b60cd5460c9546040516370a0823160e01b8152306004820152600092849290916001600160a01b03909116906370a0823190602401602060405180830381865afa158015611442573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061146691906128ad565b61147091906128c6565b61147a91906128c6565b9050600061149b6114916040860160208701612454565b61ffff1683611f14565b905082156114b5576114ad8382612856565b600060ce5590505b6114bf8383612856565b8111156114f357806114d18484612856565b604051638b1155d560e01b8152600481019290925260248201526044016107a0565b8060cd60008282546115059190612856565b90915550506040805160808082018352868301358252606087013560208301529091820190611536908701876128d9565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920182905250938552505050602091820184905260d19161158390880188612454565b61ffff1661ffff16815260200190815260200160002060008660200160208101906115ae9190612454565b61ffff16815260208082019290925260409081016000208351815591830151600183015582015160028201906115e49082612968565b50606091909101516003909101556116026040850160208601612454565b61ffff166116136020860186612454565b61ffff167fe0d35a855f045d0835580e6551869bfe8735c355ae97e25b8f5ff90c1c47084a866040013584604051611655929190918252602082015260400190565b60405180910390a35050506109596001609755565b611672611e27565b606580546001600160a01b0383166001600160a01b031990911681179091556116a36033546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b600054610100900460ff166117025760405162461bcd60e51b81526004016107a090612a28565b610afb611fd1565b600054610100900460ff166117315760405162461bcd60e51b81526004016107a090612a28565b610afb611ff8565b606580546001600160a01b031916905561095981612028565b610959611e27565b7f4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd91435460ff16156117925761178d8361207a565b505050565b826001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa9250505080156117ec575060408051601f3d908101601f191682019092526117e9918101906128ad565b60015b61184f5760405162461bcd60e51b815260206004820152602e60248201527f45524331393637557067726164653a206e657720696d706c656d656e7461746960448201526d6f6e206973206e6f74205555505360901b60648201526084016107a0565b600080516020612b2583398151915281146118be5760405162461bcd60e51b815260206004820152602960248201527f45524331393637557067726164653a20756e737570706f727465642070726f786044820152681a58589b195555525160ba1b60648201526084016107a0565b5061178d838383612116565b60ca5460009081906001600160a01b0316636352211e858584816118f0576118f0612a73565b90506020028101906119029190612a89565b604001356040518263ffffffff1660e01b815260040161192491815260200190565b602060405180830381865afa158015611941573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119659190612aa9565b905060005b83811015611d915760cf600086868481811061198857611988612a73565b905060200281019061199a9190612a89565b60409081013582526020820192909252016000205460ff1615611a37578484828181106119c9576119c9612a73565b90506020028101906119db9190612a89565b604001358585838181106119f1576119f1612a73565b9050602002810190611a039190612a89565b611a11906020810190612454565b60405163111b598760e01b8152600481019290925261ffff1660248201526044016107a0565b60ca546001600160a01b038084169116636352211e878785818110611a5e57611a5e612a73565b9050602002810190611a709190612a89565b604001356040518263ffffffff1660e01b8152600401611a9291815260200190565b602060405180830381865afa158015611aaf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ad39190612aa9565b6001600160a01b031614611af95760405162cb1d4760e11b815260040160405180910390fd5b611b20858583818110611b0e57611b0e612a73565b90506020028101906106429190612a89565b611be157848482818110611b3657611b36612a73565b9050602002810190611b489190612a89565b60400135858583818110611b5e57611b5e612a73565b9050602002810190611b709190612a89565b611b7e906020810190612454565b868684818110611b9057611b90612a73565b9050602002810190611ba29190612a89565b611bb3906040810190602001612454565b60405163d901c42760e01b8152600481019390935261ffff91821660248401521660448201526064016107a0565b600160cf6000878785818110611bf957611bf9612a73565b9050602002810190611c0b9190612a89565b60400135815260200190815260200160002060006101000a81548160ff0219169083151502179055506000611ca5868684818110611c4b57611c4b612a73565b9050602002810190611c5d9190612a89565b611c6b906020810190612454565b878785818110611c7d57611c7d612a73565b9050602002810190611c8f9190612a89565b611ca0906040810190602001612454565b612141565b9050611cb18185612856565b9350858583818110611cc557611cc5612a73565b9050602002810190611cd79190612a89565b604001357f3ab82044ca6d2b6a839a93c51f789c0c9de94113702f8532f436eddc7c9c3692878785818110611d0e57611d0e612a73565b9050602002810190611d209190612a89565b611d2e906020810190612454565b888886818110611d4057611d40612a73565b9050602002810190611d529190612a89565b611d63906040810190602001612454565b6040805161ffff9384168152929091166020830152810184905260600160405180910390a25060010161196a565b508160cd6000828254611da491906128c6565b909155505060c95460405163a9059cbb60e01b81526001600160a01b038381166004830152602482018590529091169063a9059cbb906044016020604051808303816000875af1158015611dfc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e209190612869565b5050505050565b6033546001600160a01b03163314610afb5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016107a0565b60008315611eb3578360051b8501855b803580851160051b94855260209485185260406000209301818110611e915750505b501492915050565b600260975403611f0d5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016107a0565b6002609755565b60008060008085600103611f33575083915060019050620186a0611f9d565b85600203611f6757611f4885620f4240612ac6565b9250611f5a620186a0620f42406128c6565b9150620493e09050611f9d565b611f7485620f4240612ac6565b9250620493e0611f8a620186a0620f42406128c6565b611f9491906128c6565b9150620927c090505b611faa82620f4240612ac6565b611fb48285612ac6565b611fbe9190612add565b93505050505b92915050565b6001609755565b600054610100900460ff16611fca5760405162461bcd60e51b81526004016107a090612a28565b600054610100900460ff1661201f5760405162461bcd60e51b81526004016107a090612a28565b610afb33611739565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6001600160a01b0381163b6120e75760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b60648201526084016107a0565b600080516020612b2583398151915280546001600160a01b0319166001600160a01b0392909216919091179055565b61211f83612235565b60008251118061212c5750805b1561178d5761213b8383612275565b50505050565b61ffff808316600090815260d1602090815260408083209385168352928152828220835160808101855281548152600182015492810192909252600281018054939485949084019190612193906127b5565b80601f01602080910402602001604051908101604052809291908181526020018280546121bf906127b5565b801561220c5780601f106121e15761010080835404028352916020019161220c565b820191906000526020600020905b8154815290600101906020018083116121ef57829003601f168201915b50505050508152602001600382015481525050905080600001518160600151610d999190612add565b61223e8161207a565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b606061229a8383604051806060016040528060278152602001612b45602791396122a1565b9392505050565b6060600080856001600160a01b0316856040516122be9190612aff565b600060405180830381855af49150503d80600081146122f9576040519150601f19603f3d011682016040523d82523d6000602084013e6122fe565b606091505b509150915061230f86838387612319565b9695505050505050565b60608315612388578251600003612381576001600160a01b0385163b6123815760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016107a0565b5081610d99565b610d99838381511561239d5781518083602001fd5b8060405162461bcd60e51b81526004016107a09190612b11565b6001600160a01b038116811461095957600080fd5b600080600080600060a086880312156123e457600080fd5b85356123ef816123b7565b945060208601356123ff816123b7565b9350604086013561240f816123b7565b9250606086013561241f816123b7565b9150608086013561242f816123b7565b809150509295509295909350565b803561ffff8116811461244f57600080fd5b919050565b60006020828403121561246657600080fd5b61229a8261243d565b60006020828403121561248157600080fd5b813561229a816123b7565b634e487b7160e01b600052604160045260246000fd5b600080604083850312156124b557600080fd5b82356124c0816123b7565b9150602083013567ffffffffffffffff808211156124dd57600080fd5b818501915085601f8301126124f157600080fd5b8135818111156125035761250361248c565b604051601f8201601f19908116603f0116810190838211818310171561252b5761252b61248c565b8160405282815288602084870101111561254457600080fd5b8260208601602083013760006020848301015280955050505050509250929050565b6000806020838503121561257957600080fd5b823567ffffffffffffffff8082111561259157600080fd5b818501915085601f8301126125a557600080fd5b8135818111156125b457600080fd5b8660208260051b85010111156125c957600080fd5b60209290920196919550909350505050565b6000602082840312156125ed57600080fd5b5035919050565b6000806040838503121561260757600080fd5b6126108361243d565b915061261e6020840161243d565b90509250929050565b60005b8381101561264257818101518382015260200161262a565b50506000910152565b60008151808452612663816020860160208601612627565b601f01601f19169290920160200192915050565b848152836020820152608060408201526000612696608083018561264b565b905082606083015295945050505050565b6000602082840312156126b957600080fd5b813567ffffffffffffffff8111156126d057600080fd5b82016080818503121561229a57600080fd5b6000602082840312156126f457600080fd5b813567ffffffffffffffff81111561270b57600080fd5b820160a0818503121561229a57600080fd5b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b19195b1959d85d1958d85b1b60a21b606082015260800190565b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b6163746976652070726f787960a01b606082015260800190565b600181811c908216806127c957607f821691505b6020821081036127e957634e487b7160e01b600052602260045260246000fd5b50919050565b6000808335601e1984360301811261280657600080fd5b83018035915067ffffffffffffffff82111561282157600080fd5b6020019150600581901b360382131561283957600080fd5b9250929050565b634e487b7160e01b600052601160045260246000fd5b80820180821115611fc457611fc4612840565b60006020828403121561287b57600080fd5b8151801515811461229a57600080fd5b61ffff8181168382160190808211156128a6576128a6612840565b5092915050565b6000602082840312156128bf57600080fd5b5051919050565b81810381811115611fc457611fc4612840565b6000808335601e198436030181126128f057600080fd5b83018035915067ffffffffffffffff82111561290b57600080fd5b60200191503681900382131561283957600080fd5b601f82111561178d576000816000526020600020601f850160051c810160208610156129495750805b601f850160051c820191505b8181101561087557828155600101612955565b815167ffffffffffffffff8111156129825761298261248c565b6129968161299084546127b5565b84612920565b602080601f8311600181146129cb57600084156129b35750858301515b600019600386901b1c1916600185901b178555610875565b600085815260208120601f198616915b828110156129fa578886015182559484019460019091019084016129db565b5085821015612a185787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b634e487b7160e01b600052603260045260246000fd5b60008235607e19833603018112612a9f57600080fd5b9190910192915050565b600060208284031215612abb57600080fd5b815161229a816123b7565b8082028115828204841417611fc457611fc4612840565b600082612afa57634e487b7160e01b600052601260045260246000fd5b500490565b60008251612a9f818460208701612627565b60208152600061229a602083018461264b56fe360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a264697066735822122057e0425f01a29b131f2d2f4c5f5bfb3c5f2ec4860d63f5bd2a25f02f2cef809a64736f6c63430008180033
Deployed ByteCode
0x6080604052600436106102515760003560e01c8063715018a611610139578063bbbd732e116100b6578063e0fcf93d1161007a578063e0fcf93d14610667578063e1f1c4a714610687578063e30c39781461069d578063e93fd958146106bb578063f2fde38b146106d2578063f8d67a2b146106f257600080fd5b8063bbbd732e146105cb578063c41f66f4146105e0578063ce4d7bc414610610578063ce7c2fb914610627578063cf1814bc1461064757600080fd5b8063938ece89116100fd578063938ece89146105215780639cddc9cf146105385780639e34070f14610554578063a89de24914610594578063aced1661146105ab57600080fd5b8063715018a6146104a3578063748747e6146104b857806375b4d78c146104d857806379ba5097146104ee5780638da5cb5b1461050357600080fd5b80632acfc2ca116101d25780634f1ef286116101965780634f1ef286146104175780634fc2fd041461042a57806352d1902d1461044a5780635539aa861461045f5780636839c1bd146104755780636ed93dd01461048c57600080fd5b80632acfc2ca146103a05780632bc477281461038b5780633659cfe6146103c05780633a9f6b74146103e05780634ed718bf1461040057600080fd5b806314b5b43f1161021957806314b5b43f1461030357806318b353101461031a5780632327789a1461033157806324679c3f146103755780632aad34031461038b57600080fd5b806301dd036c1461025657806304ed00ac146102935780630cff04cd146102b75780630f6110c3146102cc5780631459457a146102e1575b600080fd5b34801561026257600080fd5b5060ca54610276906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b34801561029f57600080fd5b506102a960cd5481565b60405190815260200161028a565b3480156102c357600080fd5b506102a9605a81565b3480156102d857600080fd5b506102a9600281565b3480156102ed57600080fd5b506103016102fc3660046123cc565b610707565b005b34801561030f57600080fd5b506102a9620493e081565b34801561032657600080fd5b506102a9620186a081565b34801561033d57600080fd5b5061036261034c366004612454565b60d06020526000908152604090205461ffff1681565b60405161ffff909116815260200161028a565b34801561038157600080fd5b506102a961753081565b34801561039757600080fd5b506102a9600381565b3480156103ac57600080fd5b5060c954610276906001600160a01b031681565b3480156103cc57600080fd5b506103016103db36600461246f565b61087d565b3480156103ec57600080fd5b5060cb54610276906001600160a01b031681565b34801561040c57600080fd5b506102a96215180081565b6103016104253660046124a2565b61095c565b34801561043657600080fd5b50610301610445366004612566565b610a2c565b34801561045657600080fd5b506102a9610a36565b34801561046b57600080fd5b506102a961a8c081565b34801561048157600080fd5b506102a9620e808081565b34801561049857600080fd5b506102a9620f424081565b3480156104af57600080fd5b50610301610ae9565b3480156104c457600080fd5b506103016104d336600461246f565b610afd565b3480156104e457600080fd5b506102a960ce5481565b3480156104fa57600080fd5b50610301610b80565b34801561050f57600080fd5b506033546001600160a01b0316610276565b34801561052d57600080fd5b506102a9622c2a4081565b34801561054457600080fd5b506102a9670de0b6b3a764000081565b34801561056057600080fd5b5061058461056f3660046125db565b60cf6020526000908152604090205460ff1681565b604051901515815260200161028a565b3480156105a057600080fd5b506102a9623b538081565b3480156105b757600080fd5b5060cc54610276906001600160a01b031681565b3480156105d757600080fd5b506102a9602181565b3480156105ec57600080fd5b506106006105fb3660046125f4565b610bf7565b60405161028a9493929190612677565b34801561061c57600080fd5b506102a9620927c081565b34801561063357600080fd5b506105846106423660046126a7565b610cb3565b34801561065357600080fd5b506103016106623660046125db565b610da1565b34801561067357600080fd5b506103016106823660046126e2565b610e8d565b34801561069357600080fd5b5061036261271081565b3480156106a957600080fd5b506065546001600160a01b0316610276565b3480156106c757600080fd5b506102a96241eb0081565b3480156106de57600080fd5b506103016106ed36600461246f565b61166a565b3480156106fe57600080fd5b506102a9600181565b600054610100900460ff16158080156107275750600054600160ff909116105b806107415750303b158015610741575060005460ff166001145b6107a95760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084015b60405180910390fd5b6000805460ff1916600117905580156107cc576000805461ff0019166101001790555b6107d46116db565b6107dc61170a565b6107e582611739565b60c980546001600160a01b038089166001600160a01b03199283161790925560ca805488841690831617905560cb805487841690831617905560cc8054928616929091169190911790558015610875576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050505050565b6001600160a01b037f0000000000000000000000005715d2cf651df22032cfcf041bc90a9aa68dd03f1630036108c55760405162461bcd60e51b81526004016107a09061271d565b7f0000000000000000000000005715d2cf651df22032cfcf041bc90a9aa68dd03f6001600160a01b031661090e600080516020612b25833981519152546001600160a01b031690565b6001600160a01b0316146109345760405162461bcd60e51b81526004016107a090612769565b61093d81611752565b604080516000808252602082019092526109599183919061175a565b50565b6001600160a01b037f0000000000000000000000005715d2cf651df22032cfcf041bc90a9aa68dd03f1630036109a45760405162461bcd60e51b81526004016107a09061271d565b7f0000000000000000000000005715d2cf651df22032cfcf041bc90a9aa68dd03f6001600160a01b03166109ed600080516020612b25833981519152546001600160a01b031690565b6001600160a01b031614610a135760405162461bcd60e51b81526004016107a090612769565b610a1c82611752565b610a288282600161175a565b5050565b610a2882826118ca565b6000306001600160a01b037f0000000000000000000000005715d2cf651df22032cfcf041bc90a9aa68dd03f1614610ad65760405162461bcd60e51b815260206004820152603860248201527f555550535570677261646561626c653a206d757374206e6f742062652063616c60448201527f6c6564207468726f7567682064656c656761746563616c6c000000000000000060648201526084016107a0565b50600080516020612b2583398151915290565b610af1611e27565b610afb6000611739565b565b610b05611e27565b6001600160a01b038116610b2c5760405163c941d9fb60e01b815260040160405180910390fd5b60cc80546001600160a01b0319166001600160a01b0383169081179091556040519081527f0425bcd291db1d48816f2a98edc7ecaf6dd5c64b973d9e4b3b6b750763dc6c2e9060200160405180910390a150565b60655433906001600160a01b03168114610bee5760405162461bcd60e51b815260206004820152602960248201527f4f776e61626c6532537465703a2063616c6c6572206973206e6f7420746865206044820152683732bb9037bbb732b960b91b60648201526084016107a0565b61095981611739565b60d160209081526000928352604080842090915290825290208054600182015460028301805492939192610c2a906127b5565b80601f0160208091040260200160405190810160405280929190818152602001828054610c56906127b5565b8015610ca35780601f10610c7857610100808354040283529160200191610ca3565b820191906000526020600020905b815481529060010190602001808311610c8657829003601f168201915b5050505050908060030154905084565b6000806040830135610cc86020850185612454565b610cd86040860160208701612454565b604051602001610d0c9392919092835260f091821b6001600160f01b03199081166020850152911b16602282015260240190565b604051602081830303815290604052805190602001209050600060d16000856000016020810190610d3d9190612454565b61ffff1661ffff1681526020019081526020016000206000856020016020810190610d689190612454565b61ffff1681526020810191909152604001600020600101549050610d99610d9260608601866127ef565b8385611e81565b949350505050565b80600003610dc2576040516326d23b5b60e01b815260040160405180910390fd5b8060ce6000828254610dd49190612856565b909155505060c9546040516323b872dd60e01b8152336004820152306024820152604481018390526001600160a01b03909116906323b872dd906064016020604051808303816000875af1158015610e30573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e549190612869565b5060405181815233907f9222d6d887c327442b8c6a5b3731cda3e11f9b1444cd14830bf136a2fb300fae9060200160405180910390a250565b60cc546001600160a01b03163314610eba5760405163c0fe76eb60e01b81523360048201526024016107a0565b610ec2611ebb565b610ecf6020820182612454565b61ffff16600003610ef35760405163670fe71760e01b815260040160405180910390fd5b610f036040820160208301612454565b61ffff16600003610f27576040516305c87e5560e21b815260040160405180910390fd5b6060810135610f49576040516329e7276760e11b815260040160405180910390fd5b8060400135600003610f9957610f626020820182612454565b610f726040830160208401612454565b604051636befa94f60e11b815261ffff9283166004820152911660248201526044016107a0565b600360d06000610fac6020850185612454565b61ffff90811682526020820192909252604001600020541603610fe25760405163602262d960e11b815260040160405180910390fd5b60d16000610ff36020840184612454565b61ffff1661ffff168152602001908152602001600020600082602001602081019061101e9190612454565b61ffff1681526020810191909152604001600020541561107c576110456020820182612454565b6110556040830160208401612454565b604051637279cd0360e01b815261ffff9283166004820152911660248201526044016107a0565b61108c6040820160208301612454565b61ffff1660d060006110a16020850185612454565b61ffff90811682526020820192909252604001600020546110c49116600161288b565b61ffff1614611138576110dd6040820160208301612454565b60d060006110ee6020850185612454565b61ffff90811682526020820192909252604001600020546111119116600161288b565b60405163555ec34560e11b815261ffff9283166004820152911660248201526044016107a0565b60ce54600160d0600061114e6020860186612454565b61ffff908116825260208201929092526040016000908120805490926111769185911661288b565b92506101000a81548161ffff021916908361ffff1602179055508160000160208101906111a39190612454565b61ffff1660cb60009054906101000a90046001600160a01b03166001600160a01b031663be5887456040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111fa573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061121e91906128ad565b10156112cf576112316020830183612454565b60cb60009054906101000a90046001600160a01b03166001600160a01b031663be5887456040518163ffffffff1660e01b8152600401602060405180830381865afa158015611284573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112a891906128ad565b604051631b0295a360e01b815261ffff9283166004820152911660248201526044016107a0565b60cb54604080516302ad6a1760e11b815290516001926001600160a01b03169163055ad42e9160048083019260209291908290030181865afa158015611319573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061133d91906128ad565b036113f0576113526040830160208401612454565b60cb60009054906101000a90046001600160a01b03166001600160a01b031663055ad42e6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156113a5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113c991906128ad565b604051630799a54b60e31b815261ffff9283166004820152911660248201526044016107a0565b60cd5460c9546040516370a0823160e01b8152306004820152600092849290916001600160a01b03909116906370a0823190602401602060405180830381865afa158015611442573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061146691906128ad565b61147091906128c6565b61147a91906128c6565b9050600061149b6114916040860160208701612454565b61ffff1683611f14565b905082156114b5576114ad8382612856565b600060ce5590505b6114bf8383612856565b8111156114f357806114d18484612856565b604051638b1155d560e01b8152600481019290925260248201526044016107a0565b8060cd60008282546115059190612856565b90915550506040805160808082018352868301358252606087013560208301529091820190611536908701876128d9565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920182905250938552505050602091820184905260d19161158390880188612454565b61ffff1661ffff16815260200190815260200160002060008660200160208101906115ae9190612454565b61ffff16815260208082019290925260409081016000208351815591830151600183015582015160028201906115e49082612968565b50606091909101516003909101556116026040850160208601612454565b61ffff166116136020860186612454565b61ffff167fe0d35a855f045d0835580e6551869bfe8735c355ae97e25b8f5ff90c1c47084a866040013584604051611655929190918252602082015260400190565b60405180910390a35050506109596001609755565b611672611e27565b606580546001600160a01b0383166001600160a01b031990911681179091556116a36033546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b600054610100900460ff166117025760405162461bcd60e51b81526004016107a090612a28565b610afb611fd1565b600054610100900460ff166117315760405162461bcd60e51b81526004016107a090612a28565b610afb611ff8565b606580546001600160a01b031916905561095981612028565b610959611e27565b7f4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd91435460ff16156117925761178d8361207a565b505050565b826001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa9250505080156117ec575060408051601f3d908101601f191682019092526117e9918101906128ad565b60015b61184f5760405162461bcd60e51b815260206004820152602e60248201527f45524331393637557067726164653a206e657720696d706c656d656e7461746960448201526d6f6e206973206e6f74205555505360901b60648201526084016107a0565b600080516020612b2583398151915281146118be5760405162461bcd60e51b815260206004820152602960248201527f45524331393637557067726164653a20756e737570706f727465642070726f786044820152681a58589b195555525160ba1b60648201526084016107a0565b5061178d838383612116565b60ca5460009081906001600160a01b0316636352211e858584816118f0576118f0612a73565b90506020028101906119029190612a89565b604001356040518263ffffffff1660e01b815260040161192491815260200190565b602060405180830381865afa158015611941573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119659190612aa9565b905060005b83811015611d915760cf600086868481811061198857611988612a73565b905060200281019061199a9190612a89565b60409081013582526020820192909252016000205460ff1615611a37578484828181106119c9576119c9612a73565b90506020028101906119db9190612a89565b604001358585838181106119f1576119f1612a73565b9050602002810190611a039190612a89565b611a11906020810190612454565b60405163111b598760e01b8152600481019290925261ffff1660248201526044016107a0565b60ca546001600160a01b038084169116636352211e878785818110611a5e57611a5e612a73565b9050602002810190611a709190612a89565b604001356040518263ffffffff1660e01b8152600401611a9291815260200190565b602060405180830381865afa158015611aaf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ad39190612aa9565b6001600160a01b031614611af95760405162cb1d4760e11b815260040160405180910390fd5b611b20858583818110611b0e57611b0e612a73565b90506020028101906106429190612a89565b611be157848482818110611b3657611b36612a73565b9050602002810190611b489190612a89565b60400135858583818110611b5e57611b5e612a73565b9050602002810190611b709190612a89565b611b7e906020810190612454565b868684818110611b9057611b90612a73565b9050602002810190611ba29190612a89565b611bb3906040810190602001612454565b60405163d901c42760e01b8152600481019390935261ffff91821660248401521660448201526064016107a0565b600160cf6000878785818110611bf957611bf9612a73565b9050602002810190611c0b9190612a89565b60400135815260200190815260200160002060006101000a81548160ff0219169083151502179055506000611ca5868684818110611c4b57611c4b612a73565b9050602002810190611c5d9190612a89565b611c6b906020810190612454565b878785818110611c7d57611c7d612a73565b9050602002810190611c8f9190612a89565b611ca0906040810190602001612454565b612141565b9050611cb18185612856565b9350858583818110611cc557611cc5612a73565b9050602002810190611cd79190612a89565b604001357f3ab82044ca6d2b6a839a93c51f789c0c9de94113702f8532f436eddc7c9c3692878785818110611d0e57611d0e612a73565b9050602002810190611d209190612a89565b611d2e906020810190612454565b888886818110611d4057611d40612a73565b9050602002810190611d529190612a89565b611d63906040810190602001612454565b6040805161ffff9384168152929091166020830152810184905260600160405180910390a25060010161196a565b508160cd6000828254611da491906128c6565b909155505060c95460405163a9059cbb60e01b81526001600160a01b038381166004830152602482018590529091169063a9059cbb906044016020604051808303816000875af1158015611dfc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e209190612869565b5050505050565b6033546001600160a01b03163314610afb5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016107a0565b60008315611eb3578360051b8501855b803580851160051b94855260209485185260406000209301818110611e915750505b501492915050565b600260975403611f0d5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016107a0565b6002609755565b60008060008085600103611f33575083915060019050620186a0611f9d565b85600203611f6757611f4885620f4240612ac6565b9250611f5a620186a0620f42406128c6565b9150620493e09050611f9d565b611f7485620f4240612ac6565b9250620493e0611f8a620186a0620f42406128c6565b611f9491906128c6565b9150620927c090505b611faa82620f4240612ac6565b611fb48285612ac6565b611fbe9190612add565b93505050505b92915050565b6001609755565b600054610100900460ff16611fca5760405162461bcd60e51b81526004016107a090612a28565b600054610100900460ff1661201f5760405162461bcd60e51b81526004016107a090612a28565b610afb33611739565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6001600160a01b0381163b6120e75760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b60648201526084016107a0565b600080516020612b2583398151915280546001600160a01b0319166001600160a01b0392909216919091179055565b61211f83612235565b60008251118061212c5750805b1561178d5761213b8383612275565b50505050565b61ffff808316600090815260d1602090815260408083209385168352928152828220835160808101855281548152600182015492810192909252600281018054939485949084019190612193906127b5565b80601f01602080910402602001604051908101604052809291908181526020018280546121bf906127b5565b801561220c5780601f106121e15761010080835404028352916020019161220c565b820191906000526020600020905b8154815290600101906020018083116121ef57829003601f168201915b50505050508152602001600382015481525050905080600001518160600151610d999190612add565b61223e8161207a565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b606061229a8383604051806060016040528060278152602001612b45602791396122a1565b9392505050565b6060600080856001600160a01b0316856040516122be9190612aff565b600060405180830381855af49150503d80600081146122f9576040519150601f19603f3d011682016040523d82523d6000602084013e6122fe565b606091505b509150915061230f86838387612319565b9695505050505050565b60608315612388578251600003612381576001600160a01b0385163b6123815760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016107a0565b5081610d99565b610d99838381511561239d5781518083602001fd5b8060405162461bcd60e51b81526004016107a09190612b11565b6001600160a01b038116811461095957600080fd5b600080600080600060a086880312156123e457600080fd5b85356123ef816123b7565b945060208601356123ff816123b7565b9350604086013561240f816123b7565b9250606086013561241f816123b7565b9150608086013561242f816123b7565b809150509295509295909350565b803561ffff8116811461244f57600080fd5b919050565b60006020828403121561246657600080fd5b61229a8261243d565b60006020828403121561248157600080fd5b813561229a816123b7565b634e487b7160e01b600052604160045260246000fd5b600080604083850312156124b557600080fd5b82356124c0816123b7565b9150602083013567ffffffffffffffff808211156124dd57600080fd5b818501915085601f8301126124f157600080fd5b8135818111156125035761250361248c565b604051601f8201601f19908116603f0116810190838211818310171561252b5761252b61248c565b8160405282815288602084870101111561254457600080fd5b8260208601602083013760006020848301015280955050505050509250929050565b6000806020838503121561257957600080fd5b823567ffffffffffffffff8082111561259157600080fd5b818501915085601f8301126125a557600080fd5b8135818111156125b457600080fd5b8660208260051b85010111156125c957600080fd5b60209290920196919550909350505050565b6000602082840312156125ed57600080fd5b5035919050565b6000806040838503121561260757600080fd5b6126108361243d565b915061261e6020840161243d565b90509250929050565b60005b8381101561264257818101518382015260200161262a565b50506000910152565b60008151808452612663816020860160208601612627565b601f01601f19169290920160200192915050565b848152836020820152608060408201526000612696608083018561264b565b905082606083015295945050505050565b6000602082840312156126b957600080fd5b813567ffffffffffffffff8111156126d057600080fd5b82016080818503121561229a57600080fd5b6000602082840312156126f457600080fd5b813567ffffffffffffffff81111561270b57600080fd5b820160a0818503121561229a57600080fd5b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b19195b1959d85d1958d85b1b60a21b606082015260800190565b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b6163746976652070726f787960a01b606082015260800190565b600181811c908216806127c957607f821691505b6020821081036127e957634e487b7160e01b600052602260045260246000fd5b50919050565b6000808335601e1984360301811261280657600080fd5b83018035915067ffffffffffffffff82111561282157600080fd5b6020019150600581901b360382131561283957600080fd5b9250929050565b634e487b7160e01b600052601160045260246000fd5b80820180821115611fc457611fc4612840565b60006020828403121561287b57600080fd5b8151801515811461229a57600080fd5b61ffff8181168382160190808211156128a6576128a6612840565b5092915050565b6000602082840312156128bf57600080fd5b5051919050565b81810381811115611fc457611fc4612840565b6000808335601e198436030181126128f057600080fd5b83018035915067ffffffffffffffff82111561290b57600080fd5b60200191503681900382131561283957600080fd5b601f82111561178d576000816000526020600020601f850160051c810160208610156129495750805b601f850160051c820191505b8181101561087557828155600101612955565b815167ffffffffffffffff8111156129825761298261248c565b6129968161299084546127b5565b84612920565b602080601f8311600181146129cb57600084156129b35750858301515b600019600386901b1c1916600185901b178555610875565b600085815260208120601f198616915b828110156129fa578886015182559484019460019091019084016129db565b5085821015612a185787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b634e487b7160e01b600052603260045260246000fd5b60008235607e19833603018112612a9f57600080fd5b9190910192915050565b600060208284031215612abb57600080fd5b815161229a816123b7565b8082028115828204841417611fc457611fc4612840565b600082612afa57634e487b7160e01b600052601260045260246000fd5b500490565b60008251612a9f818460208701612627565b60208152600061229a602083018461264b56fe360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a264697066735822122057e0425f01a29b131f2d2f4c5f5bfb3c5f2ec4860d63f5bd2a25f02f2cef809a64736f6c63430008180033