Verified contractExactMIT
PSTRAT
Address0xce8d00ddf8ebf245043e261df89739e2fd114c66
- Balance
0.010994 ETH
- Transactions
155
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,964,864
- Creation transaction
- 0x33afb1c0fd…bc38297291
13 files
- contracts/PSTRAT.solmain24.07 KB
- @openzeppelin/contracts/access/Ownable.sol3.1 KB
- @openzeppelin/contracts/interfaces/draft-IERC6093.sol6.54 KB
- @openzeppelin/contracts/token/ERC20/ERC20.sol10.8 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- @openzeppelin/contracts/token/ERC721/IERC721.sol4.93 KB
- @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol997 B
- @openzeppelin/contracts/utils/Context.sol963 B
- @openzeppelin/contracts/utils/ReentrancyGuard.sol4.77 KB
- @openzeppelin/contracts/utils/StorageSlot.sol4.18 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol871 B
- contracts/interfaces/IUniswapV2.sol988 B
contracts/PSTRAT.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/*
* ____ ____ _____ ____ _ _____
* | _ \/ ___|_ _| _ \ / \|_ _|
* | |_) \___ \ | | | |_) | / _ \ | |
* | __/ ___) || | | _ < / ___ \| |
* |_| |____/ |_| |_| \_\/_/ \_\_|
*
* PSTRAT - NFT MicroStrategy Token
*
* Author : https://github.com/jtaaa
* X / Twitter: https://x.com/PudgySTRAT
* Treasury target: PudgyPenguins (PPG) at 0xBd3531dA5CF5857e7CfAA92426877b022e612cf8
*/
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {IUniswapV2Factory, IUniswapV2Router02} from "./interfaces/IUniswapV2.sol";
/**
* @title PSTRAT - NFT MicroStrategy Token
* @author https://github.com/jtaaa
* @notice ERC20 with a 3% buy/sell tax targeting PudgyPenguins (PPG) at
* 0xBd3531dA5CF5857e7CfAA92426877b022e612cf8 as the treasury asset.
*
* Launch flow (zero pre-launch holders):
* 1) deploy() - mints the entire 1B supply to THIS contract.
* nobody holds tokens; trading is closed.
* 2) owner sends ETH - 1 ETH (or whatever) is transferred into the
* contract's balance.
* 3) openTrading() - one-shot owner call: pairs 80% of supply
* with the contract's ETH on Uniswap V2,
* vaults the LP, and flips trading on.
* 4) airdrop() - owner distributes the remaining 20% to
* arbitrary recipients off the AMM path.
*
* Steady state:
* - 3% buy/sell tax accrues inside the contract.
* - Tax auto-swaps to ETH on Uniswap V2 when the threshold is reached.
* - ETH stays as treasury; owner uses harvest() to buy Pudgy NFTs
* off-chain, then transfers them back into the contract.
* - All assets (PSTRAT tax, ETH, LP, NFTs) live inside this address.
*
* The contract intentionally does NOT integrate with any specific NFT
* marketplace, keeping the on-chain surface minimal and secure.
*/
contract PSTRAT is ERC20, Ownable, ReentrancyGuard, IERC721Receiver {
// ---------------------------------------------------------------------
// Constants & immutables
// ---------------------------------------------------------------------
uint256 public constant TOTAL_SUPPLY = 1_000_000_000 ether; // 1B * 1e18
/// @notice Share of supply seeded into the Uniswap V2 pool by `openTrading()`.
/// @dev 80% (800M) of TOTAL_SUPPLY. The remaining 20% stays in the contract
/// and is distributed off the Uniswap path via `airdrop()`.
uint16 public constant LIQUIDITY_BPS = 8_000;
/// @notice Hard cap for tax bps (5% per side) to prevent owner abuse.
uint16 public constant MAX_TAX_BPS = 500;
/// @notice Basis points denominator.
uint16 public constant BPS_DENOMINATOR = 10_000;
// ---------------------------------------------------------------------
// Uniswap V2
// ---------------------------------------------------------------------
IUniswapV2Router02 public immutable uniswapRouter;
address public immutable uniswapPair;
// ---------------------------------------------------------------------
// Tax configuration
// ---------------------------------------------------------------------
/// @notice Total buy/sell tax in basis points (default 300 = 3%).
uint16 public buyTaxBps = 300;
uint16 public sellTaxBps = 300;
/// @notice How collected ETH is split: nftTreasuryBps + marketingBps == BPS_DENOMINATOR.
uint16 public nftTreasuryBps = 10_000; // 100% to NFT treasury (held in this contract)
uint16 public marketingBps = 0;
/// @notice Marketing payout wallet. Receives `marketingBps` share after each swap.
address public marketingWallet;
/// @notice Token amount that triggers an auto swap-to-ETH in `_update`.
uint256 public swapThreshold = 500_000 ether; // 0.05% of supply by default
/// @notice Hard ceiling on tokens swapped per trigger (anti-impact).
uint256 public maxSwapPerTrigger = 5_000_000 ether;
/// @notice Toggle to disable auto swap (e.g. for migrations).
bool public swapEnabled = true;
/// @notice Reentrancy guard for the internal swap path triggered from `_update`.
bool private _inSwap;
/// @notice Addresses excluded from buy/sell tax (treasury, router, owner, etc.).
mapping(address => bool) public isExcludedFromFee;
/// @notice AMM pairs that incur buy/sell tax. The primary pair is auto-set; extras may be added.
mapping(address => bool) public isAmmPair;
/// @notice Once true, the public can transfer/buy/sell PSTRAT freely. Until then,
/// only fee-excluded addresses (this contract, owner, router) may move tokens —
/// which lets the contract seed the LP and execute airdrops, while preventing
/// any pre-launch sniping or back-door distribution.
bool public tradingOpen;
/// @notice Tokens reserved for non-tax distribution (LP seeding + airdrops).
/// Auto-swap and manualSwap are STRICTLY forbidden from touching this
/// portion: only the surplus `balanceOf(this) - airdropReserve` is
/// considered tax revenue and swappable to ETH.
/// Lifecycle:
/// - Constructor: 1B (entire supply, since the contract holds it all)
/// - openTrading(): -800M (the LP seed) → 200M remains
/// - airdrop(...): -amounts → ramps down to 0
uint256 public airdropReserve;
// ---------------------------------------------------------------------
// Events
// ---------------------------------------------------------------------
event TaxBpsUpdated(uint16 buyTaxBps, uint16 sellTaxBps);
event TaxSplitUpdated(uint16 nftTreasuryBps, uint16 marketingBps);
event MarketingWalletUpdated(address indexed wallet);
event SwapThresholdUpdated(uint256 threshold, uint256 maxPerTrigger);
event SwapEnabledUpdated(bool enabled);
event ExcludedFromFee(address indexed account, bool excluded);
event AmmPairUpdated(address indexed pair, bool isPair);
event AutoSwap(uint256 tokensSwapped, uint256 ethReceived, uint256 toMarketing);
event Harvested(address indexed to, uint256 amount);
event NFTWithdrawn(address indexed nft, uint256 indexed tokenId, address indexed to);
event ERC20Rescued(address indexed token, address indexed to, uint256 amount);
event TradingOpened(uint256 lpTokens, uint256 ethAdded);
event AirdropExecuted(uint256 recipients, uint256 totalAmount);
// ---------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------
error TaxTooHigh();
error InvalidSplit();
error InvalidThreshold();
error ZeroAddress();
error ETHTransferFailed();
error CannotRescueSelf();
error TradingNotOpen();
error TradingAlreadyOpen();
error LengthMismatch();
error NoEthForLiquidity();
error InsufficientTokenBalance();
error InsufficientAirdropReserve();
error NoTaxToSwap();
error AmountExceedsTaxBalance();
// ---------------------------------------------------------------------
// Constructor
// ---------------------------------------------------------------------
/**
* @param router_ Uniswap V2 router (mainnet: 0x7a25...488D)
* @param initialOwner_ Initial owner / deployer
*/
constructor(address router_, address initialOwner_)
ERC20("PSTRAT", "PSTRAT")
Ownable(initialOwner_)
{
if (router_ == address(0) || initialOwner_ == address(0)) revert ZeroAddress();
uniswapRouter = IUniswapV2Router02(router_);
// Create WETH/PSTRAT pair on deploy.
address pair = IUniswapV2Factory(uniswapRouter.factory())
.createPair(address(this), uniswapRouter.WETH());
uniswapPair = pair;
isAmmPair[pair] = true;
// Default fee exclusions.
isExcludedFromFee[initialOwner_] = true;
isExcludedFromFee[address(this)] = true;
isExcludedFromFee[router_] = true;
marketingWallet = initialOwner_;
// Mint the entire supply to the contract itself. No external party holds
// PSTRAT until `openTrading()` seeds the pool and `airdrop()` distributes
// the remaining 20%. This eliminates any pre-launch holder.
_mint(address(this), TOTAL_SUPPLY);
// Initially the entire supply is "non-tax" reserve. openTrading() will
// burn the LP slice; airdrop() will burn the distribution slice.
airdropReserve = TOTAL_SUPPLY;
}
// ---------------------------------------------------------------------
// ERC20 transfer override (tax + auto-swap)
// ---------------------------------------------------------------------
/**
* @dev OZ v5 hooks all balance changes through `_update`. We intercept here to:
* 1) Auto-swap accumulated tax tokens to ETH on sells (when threshold met).
* 2) Apply 3% buy/sell tax for AMM-pair interactions.
*/
function _update(address from, address to, uint256 value) internal override {
// Mint / burn paths: no tax, no swap logic.
if (from == address(0) || to == address(0)) {
super._update(from, to, value);
return;
}
// Pre-launch transfer guard: until `openTrading()` is called, only the
// contract itself, the owner, and other fee-excluded addresses can move
// tokens. This is what allows the contract to seed the pool and run
// airdrops while preventing any third-party from owning PSTRAT or
// sniping the pool before it exists.
if (!tradingOpen && !isExcludedFromFee[from] && !isExcludedFromFee[to]) {
revert TradingNotOpen();
}
// Auto swap on sells (transfers TO the AMM pair) before applying tax,
// so that newly collected tax becomes ETH on the next sell.
bool isSell = isAmmPair[to];
bool isBuy = isAmmPair[from];
if (
swapEnabled &&
!_inSwap &&
isSell &&
!isExcludedFromFee[from] &&
!isExcludedFromFee[to]
) {
// Only swap the *tax surplus*; never touch the airdrop reserve.
uint256 swappable = swappableTax();
if (swappable >= swapThreshold) {
uint256 toSwap = swappable > maxSwapPerTrigger ? maxSwapPerTrigger : swappable;
_swapTokensForEthAndDistribute(toSwap, true /* swallowErrors */);
}
}
// Tax is applied only on AMM buys/sells, never on plain wallet transfers.
bool takeFee =
!_inSwap &&
(isBuy || isSell) &&
!isExcludedFromFee[from] &&
!isExcludedFromFee[to];
if (takeFee) {
uint16 taxBps = isBuy ? buyTaxBps : sellTaxBps;
uint256 fee = (value * taxBps) / BPS_DENOMINATOR;
if (fee > 0) {
super._update(from, address(this), fee);
value -= fee;
}
}
super._update(from, to, value);
}
// ---------------------------------------------------------------------
// Auto-swap: PSTRAT -> ETH via Uniswap V2
// ---------------------------------------------------------------------
/**
* @dev Two-mode swap helper.
* - `swallowErrors=true` (auto-swap inside `_update`): a router
* revert is caught so a user's sell can never be bricked. Tax
* tokens stay in the contract for the next attempt.
* - `swallowErrors=false` (owner's `manualSwap`): the call propagates
* revert reasons, so the owner can see exactly why a rescue swap
* failed.
*/
function _swapTokensForEthAndDistribute(uint256 tokenAmount, bool swallowErrors) private {
_inSwap = true;
uint256 ethBefore = address(this).balance;
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapRouter.WETH();
_approve(address(this), address(uniswapRouter), tokenAmount);
if (swallowErrors) {
try uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount, 0, path, address(this), block.timestamp
) {
_afterSwap(tokenAmount, address(this).balance - ethBefore);
} catch {
// Tokens remain in the contract; next sell or manualSwap can retry.
}
} else {
uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount, 0, path, address(this), block.timestamp
);
_afterSwap(tokenAmount, address(this).balance - ethBefore);
}
_inSwap = false;
}
function _afterSwap(uint256 tokenAmount, uint256 ethGained) private {
uint256 toMarketing;
if (ethGained > 0 && marketingBps > 0 && marketingWallet != address(0)) {
toMarketing = (ethGained * marketingBps) / BPS_DENOMINATOR;
if (toMarketing > 0) {
(bool ok, ) = marketingWallet.call{value: toMarketing}("");
// Marketing failures are swallowed unconditionally — user sells must
// never break because the marketing wallet is a contract that
// refuses ETH. Funds simply stay in the treasury.
if (!ok) toMarketing = 0;
}
}
emit AutoSwap(tokenAmount, ethGained, toMarketing);
}
/**
* @notice Owner's last-resort: convert accumulated tax tokens to ETH on demand.
* Useful when `swapEnabled` was toggled off, the threshold was lowered,
* or auto-swap kept failing during normal trading and ETH must be
* recovered out of the tax pool.
*
* @param tokenAmount amount of tax tokens to swap. Pass `0` to swap the entire
* `swappableTax()` balance in one go (the rescue mode).
*
* @dev Strict: any router revert propagates so the owner sees the failure.
* Cannot touch the airdrop reserve — `tokenAmount` is bounded by
* `swappableTax()`.
*/
function manualSwap(uint256 tokenAmount) external onlyOwner {
uint256 swappable = swappableTax();
if (swappable == 0) revert NoTaxToSwap();
if (tokenAmount == 0) tokenAmount = swappable;
if (tokenAmount > swappable) revert AmountExceedsTaxBalance();
_swapTokensForEthAndDistribute(tokenAmount, false /* strict */);
}
/**
* @notice Returns the portion of `balanceOf(this)` that is tax revenue and
* therefore eligible for swap-to-ETH. The airdrop reserve is excluded.
*/
function swappableTax() public view returns (uint256) {
uint256 bal = balanceOf(address(this));
return bal > airdropReserve ? bal - airdropReserve : 0;
}
// ---------------------------------------------------------------------
// Launch: seed Uniswap V2 pool + open public trading
// ---------------------------------------------------------------------
/**
* @notice Owner one-shot launch: pair `LIQUIDITY_BPS` (default 80%) of total
* supply with the entire ETH balance currently held by this contract,
* mint LP tokens to this contract (vaulted), and flip `tradingOpen`
* on so the public can trade.
*
* Optionally accepts msg.value to top up ETH at the same call. Any
* ETH already deposited beforehand (e.g. via a plain transfer) is
* used too.
*
* The remaining 20% of supply stays in the contract for `airdrop()`.
*
* @dev Reverts if already open, if the contract does not hold the required
* 80% of supply, or if there is no ETH to seed the pool with.
*/
function openTrading() external payable onlyOwner nonReentrant {
if (tradingOpen) revert TradingAlreadyOpen();
uint256 lpTokens = (TOTAL_SUPPLY * LIQUIDITY_BPS) / BPS_DENOMINATOR;
if (balanceOf(address(this)) < lpTokens) revert InsufficientTokenBalance();
uint256 ethForLP = address(this).balance; // includes any msg.value
if (ethForLP == 0) revert NoEthForLiquidity();
_approve(address(this), address(uniswapRouter), lpTokens);
uniswapRouter.addLiquidityETH{value: ethForLP}(
address(this),
lpTokens,
0, // accept any token amount (we control both sides at launch)
0, // accept any ETH amount
address(this), // LP receiver = this contract (vaulted)
block.timestamp
);
// Burn the LP slice from the airdrop reserve. The remaining 200M is
// what `airdrop()` is allowed to distribute.
airdropReserve -= lpTokens;
tradingOpen = true;
emit TradingOpened(lpTokens, ethForLP);
}
/**
* @notice Batch-airdrop PSTRAT held by the contract to arbitrary recipients.
* Intended for distributing the 20% supply reserved after `openTrading()`,
* but can be called any time to send tokens directly out of the vault
* (e.g. to seed a CEX listing wallet, partnerships, etc.).
*
* @dev Tax-free: the contract is fee-excluded so `_update` skips tax/auto-swap.
* Caller MUST ensure `recipients.length == amounts.length` and that the
* contract holds at least the sum of `amounts`.
*/
function airdrop(address[] calldata recipients, uint256[] calldata amounts)
external
onlyOwner
nonReentrant
{
uint256 len = recipients.length;
if (len != amounts.length) revert LengthMismatch();
// Pre-compute total to enforce the reserve cap atomically. This makes
// it impossible to over-airdrop and accidentally drain tax revenue.
uint256 total;
for (uint256 i; i < len; ) {
address to = recipients[i];
if (to == address(0)) revert ZeroAddress();
unchecked {
total += amounts[i];
++i;
}
// Touch `to` once for the zero-check; transfer happens in the second loop.
}
if (total > airdropReserve) revert InsufficientAirdropReserve();
airdropReserve -= total;
for (uint256 i; i < len; ) {
_transfer(address(this), recipients[i], amounts[i]);
unchecked { ++i; }
}
emit AirdropExecuted(len, total);
}
// ---------------------------------------------------------------------
// Treasury actions (owner-only)
// ---------------------------------------------------------------------
/**
* @notice Harvest treasury ETH for owner-led operations such as off-chain
* NFT acquisitions on OpenSea / Blur. The owner withdraws operational
* funds, executes the buy, and returns purchased NFTs to the contract.
*/
function harvest(address to, uint256 amount) external onlyOwner nonReentrant {
if (to == address(0)) revert ZeroAddress();
(bool ok, ) = to.call{value: amount}("");
if (!ok) revert ETHTransferFailed();
emit Harvested(to, amount);
}
/// @notice Pull an ERC721 from the treasury (e.g. to sell off-chain).
function withdrawNFT(address nft, uint256 tokenId, address to) external onlyOwner nonReentrant {
if (nft == address(0) || to == address(0)) revert ZeroAddress();
IERC721(nft).safeTransferFrom(address(this), to, tokenId);
emit NFTWithdrawn(nft, tokenId, to);
}
/// @notice Batch NFT withdrawal helper.
function withdrawNFTBatch(
address nft,
uint256[] calldata tokenIds,
address to
) external onlyOwner nonReentrant {
if (nft == address(0) || to == address(0)) revert ZeroAddress();
IERC721 nftContract = IERC721(nft);
uint256 len = tokenIds.length;
for (uint256 i; i < len; ) {
nftContract.safeTransferFrom(address(this), to, tokenIds[i]);
emit NFTWithdrawn(nft, tokenIds[i], to);
unchecked { ++i; }
}
}
/// @notice Rescue arbitrary ERC20 tokens accidentally sent here.
/// @dev Cannot pull PSTRAT itself - tax tokens must go through the swap path.
function rescueERC20(address token, address to, uint256 amount) external onlyOwner nonReentrant {
if (token == address(this)) revert CannotRescueSelf();
if (to == address(0)) revert ZeroAddress();
IERC20(token).transfer(to, amount);
emit ERC20Rescued(token, to, amount);
}
// ---------------------------------------------------------------------
// Owner configuration
// ---------------------------------------------------------------------
function setTaxBps(uint16 newBuyTaxBps, uint16 newSellTaxBps) external onlyOwner {
if (newBuyTaxBps > MAX_TAX_BPS || newSellTaxBps > MAX_TAX_BPS) revert TaxTooHigh();
buyTaxBps = newBuyTaxBps;
sellTaxBps = newSellTaxBps;
emit TaxBpsUpdated(newBuyTaxBps, newSellTaxBps);
}
function setTaxSplit(uint16 newNftBps, uint16 newMarketingBps) external onlyOwner {
if (uint256(newNftBps) + uint256(newMarketingBps) != BPS_DENOMINATOR) revert InvalidSplit();
nftTreasuryBps = newNftBps;
marketingBps = newMarketingBps;
emit TaxSplitUpdated(newNftBps, newMarketingBps);
}
function setMarketingWallet(address newWallet) external onlyOwner {
if (newWallet == address(0)) revert ZeroAddress();
marketingWallet = newWallet;
emit MarketingWalletUpdated(newWallet);
}
function setSwapThreshold(uint256 newThreshold, uint256 newMaxPerTrigger) external onlyOwner {
if (newThreshold == 0 || newMaxPerTrigger < newThreshold) revert InvalidThreshold();
swapThreshold = newThreshold;
maxSwapPerTrigger = newMaxPerTrigger;
emit SwapThresholdUpdated(newThreshold, newMaxPerTrigger);
}
function setSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
emit SwapEnabledUpdated(enabled);
}
function setExcludedFromFee(address account, bool excluded) external onlyOwner {
isExcludedFromFee[account] = excluded;
emit ExcludedFromFee(account, excluded);
}
function setAmmPair(address pair, bool isPair) external onlyOwner {
if (pair == address(0)) revert ZeroAddress();
isAmmPair[pair] = isPair;
emit AmmPairUpdated(pair, isPair);
}
// ---------------------------------------------------------------------
// ERC721 receive hook (treasury can hold any NFT)
// ---------------------------------------------------------------------
function onERC721Received(
address, /* operator */
address, /* from */
uint256, /* tokenId */
bytes calldata /* data */
) external pure override returns (bytes4) {
return IERC721Receiver.onERC721Received.selector;
}
// ---------------------------------------------------------------------
// Receive ETH (from Uniswap router during swap, or direct funding)
// ---------------------------------------------------------------------
receive() external payable {}
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.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.
*
* The initial owner is set to the address provided by the deployer. 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 Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @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 {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @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 {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_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);
}
}
@openzeppelin/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
@openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @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 ERC-721 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 ERC-721
* 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 address zero.
*
* 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);
}
@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity >=0.5.0;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @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);
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @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 Context {
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;
}
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.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 EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* 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].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// 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;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = 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();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @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 ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 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) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
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) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
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) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @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[ERC 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);
}
contracts/interfaces/IUniswapV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
Compiler settingsShow
{
"viaIR": false,
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.